多播委托是否为每个链接创建新的引用?

Is multicast delegate create new reference for each chaining?

多播委托是否为每个链接创建新的引用?或者它是一个值类型(MSDN 另有说明)?不懂,请看下面代码

using System;
class TestClass
{
    static void Main()
    {
        Action origin = new Action(() => { Console.WriteLine("1st line"); });
        Action copyFromOrigin;

        copyFromOrigin = origin;
        origin += new Action(() => { Console.WriteLine("2nd line"); });

        copyFromOrigin.Invoke();

        //result is "1st line", why the "2nd line" is missing? 
        //shouldn't the copyFromOrigin is referencing the origin?
        Console.ReadKey();
    }
}

因为它是不可变类型,并且每次赋值都会创建从原始实例复制的新实例。请注意,它仍然是引用类型,但只是一种特殊类型。

委托是不可变的....

当您添加新的处理程序时,会创建一个新的 委托

在后台它调用 Delegate.Combine Method

Concatenates the invocation lists of two delegates.

Returns

A new delegate with an invocation list that concatenates the invocation lists of a and b in that order. Returns a if b is null, returns b if a is a null reference, and returns a null reference if both a and b are null references.

你可以看到它的实际效果here

Action action = <>c.<>9__0_0 ?? (<>c.<>9__0_0 = new Action(<>c.<>9.<M>b__0_0));
Action action2 = action;
action = (Action)Delegate.Combine(action, <>c.<>9__0_1 ?? (<>c.<>9__0_1 = new Action(<>c.<>9.<M>b__0_1)));
action2();
Console.ReadKey();