首页 > 解决方案 > 多播委托是否为每个链接创建新的参考?

问题描述

多播委托是否为每个链接创建新的参考?还是它的值类型(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();
    }
}

标签: c#delegatesmulticast

解决方案


代表是不可变的......

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

在引擎盖下它调用了Delegate.Combine 方法

连接两个委托的调用列表。

退货

具有调用列表的新委托,该列表按该顺序连接 a 和 b 的调用列表。如果 b 为空,则返回 a,如果 a 为空引用,则返回 b,如果 a 和 b 均为空引用,则返回空引用。

你可以在这里看到它的作用

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();

推荐阅读