c# - 多播委托是否为每个链接创建新的参考?
问题描述
多播委托是否为每个链接创建新的参考?还是它的值类型(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 方法
连接两个委托的调用列表。
退货
具有调用列表的新委托,该列表按该顺序连接 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();
推荐阅读
- javascript - 如何仅使用其名称而不知道其文件扩展名来定位文件系统中的文件
- django - NOT NULL 约束失败:products_order.user_id 尝试保存序列化程序 django 休息框架工作时
- flutter - Firebase 身份验证不适用于共享首选项
- xamarin - Xamarin BindableProperty 值优先级
- r - R如何按条件加入data.table?
- html - 在 ng-circle-progress 的外部笔划中添加自定义 css
- netsuite - 在 NetSuite 中,如何在转移订单上显示现有、可用和优先股级别?
- unicode - 字符是由像素组成的吗?
- bash - 指向两个不同位置的 Azure 管道工作目录
- c# - 如何保护 Razor 类库中的控制器