开发者

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

开发者 https://www.devze.com 2023-03-28 06:25 出处:网络
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

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


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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号