gpt4 book ai didi

c# - 委托(delegate)是不可变的,但是如何呢?

转载 作者:太空狗 更新时间:2023-10-29 20:51:12 26 4
gpt4 key购买 nike

当我向现有委托(delegate)添加方法时会发生什么?我的意思是当我将 method1 添加到 del 时,del 保存了 method1 的地址。当我之后添加 method2 时,del 仍然指向 Method1 并且 Method 2 地址被插入到它的底部。这不是说我换了委托(delegate)吗?如果我可以改变这一点,为什么书中会说“委托(delegate)是不可变的”?

MyDel del = method1; 
del += method2;
del += method3;

最佳答案

您没有更改 Delegate 对象 - 您正在更改 del 以引用不同的对象。

它与字符串完全相同。让我们将您的代码转换成相同的东西,但使用字符串:

string str = "x";
str += "y";
str += "z";

您最终得到 str,它引用了一个内容为 "xyz" 的字符串对象。但是您还没有修改内容为 "x""y""z" 的字符串对象。

委托(delegate)也是如此。

del += method2;

相当于:

del = del + method2;

相当于:

del = (MyDel) Delegate.Combine(del, method2);

换句话说,“创建一个新的委托(delegate)对象,它具有引用现有两个委托(delegate)对象的调用列表”。 (如果 delmethod2 为空,则不需要创建新对象。)

参见 Delegate.Combine了解更多详情。

关于c# - 委托(delegate)是不可变的,但是如何呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40482822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com