如果委托是不可变的,为什么我可以做 x += y 之类的事情?
阅读深入了解 C#,第二版,有关组合和删除委托的 2.1.2 节。
该小节标题指出“委托是不可变的”并且“关于它们的任何内容都不能更改”。不过,在下一段中,它讨论了使用诸如
x += y;
x 和 y 是兼容委托类型的变量之类的构造。
我不是刚刚改变了x
吗?或者当我执行此操作时(即立即)处理 x
时,不变性部分是否会处理?
Reading C# In Depth, 2nd edition, section 2.1.2 on combining and removing delegates.
The subsection title states that "delegates are immutable" and that "nothing about them can be changed." In the next paragraph, though, it talks about using constructs like
x += y;
where x
and y
are variables of compatible delegate types.
Didn't I just change x
? Or does the immutability part deal with when x
is disposed of when I do this (i.e., immediately)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就像这样做:
字符串也是不可变的。上面的代码没有更改字符串 objects - 它将
x
设置为不同的值。您需要区分变量和对象。如果类型是不可变的,则意味着在构造该类型的实例后,您无法更改该类型的实例中的数据。不过,您可以为该类型的变量赋予不同的值。
如果您了解字符串如何工作,那么委托也同样如此。 += 实际上调用了 Delegate.Combine,因此:
相当于:
它不会更改
x
之前 引用的委托对象的任何内容 - 它只是创建一个新委托对象并为x
分配一个引用该新委托的值。That's like doing:
Strings are immutable too. The code above not changing the string objects - it's setting
x
to a different value.You need to differentiate between variables and objects. If a type is immutable, that means that you can't change the data within an instance of that type after it's been constructed. You can give a variable of that type a different value though.
If you understand how that works with strings, exactly the same thing is true with delegates. The += actually called Delegate.Combine, so this:
is equivalent to:
It doesn't change anything about the delegate object that
x
previously referred to - it just creates a new delegate object and assignsx
a value which refers to that new delegate.您已更改
x
,但未更改其值(即它所持有的委托)。它等同于:
You have changed
x
, but didn't change its value (i.e. the delegate it was holding).It's the same as: