如果委托是不可变的,为什么我可以做 x += y 之类的事情?

发布于 2024-11-29 05:21:05 字数 254 浏览 0 评论 0原文

阅读深入了解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

思念满溢 2024-12-06 05:21:05

这就像这样做:

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

x += y;

字符串也是不可变的。上面的代码没有更改字符串 objects - 它将 x 设置为不同的值。

您需要区分变量对象。如果类型是不可变的,则意味着在构造该类型的实例后,您无法更改该类型的实例中的数据。不过,您可以为该类型的变量赋予不同的值。

如果您了解字符串如何工作,那么委托也同样如此。 += 实际上调用了 Delegate.Combine,因此:

x += y;

相当于:

x = Delegate.Combine(x, y);

它不会更改 x 之前 引用的委托对象的任何内容 - 它只是创建一个委托对象并为x分配一个引用该新委托的值。

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.

荒人说梦 2024-12-06 05:21:05

您已更改x,但未更改其值(即它所持有的委托)。

它等同于:

int num = 4;
num += 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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文