-->

If delegates are immutable, why can I do things li

2020-05-25 08:22发布

问题:

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;