If delegates are immutable, why can I do things like x += y?

限于喜欢 提交于 2019-12-03 11:53:00

问题


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)?


回答1:


That's like doing:

string x = "x";
string y = "y";

x += y;

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:

x += y;

is equivalent to:

x = Delegate.Combine(x, y);

It doesn't change anything about the delegate object that x previously referred to - it just creates a new delegate object and assigns x a value which refers to that new delegate.




回答2:


You have changed x, but didn't change its value (i.e. the delegate it was holding).

It's the same as:

int num = 4;
num += 2;


来源:https://stackoverflow.com/questions/7043860/if-delegates-are-immutable-why-can-i-do-things-like-x-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!