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

对着背影说爱祢 提交于 2019-12-03 02:32:17

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