如果代表是不可改变的,我为什么不能做的事情一样X + = Y? [英] If delegates are immutable, why can I do things like x += y?

查看:133
本文介绍了如果代表是不可改变的,我为什么不能做的事情一样X + = Y?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读的 C#的深入,第二版的,结合上和去除代表2.1.2节。

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;



其中, X 是兼容的委托类型的变量。

where x and y are variables of compatible delegate types.

难道我只是改变 X ?还是不可改变的部分处理时 X 配置当我做这个(即,立即)?

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

推荐答案

这就像做:

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

x += y;



字符串是不可变过。上述不改变串代码的对象的 - 它的设置 X 为不同的值

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.

如果您了解如何与弦的作品,完全一样的东西是真实的与代表。在+ =居然叫Delegate.Combine,所以这个:

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



这并不改变关于委托对象的任何X 之前的简称 - 它只是创建的新的的委托对象和受让人 X 这是指一个值新的委托。

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.

这篇关于如果代表是不可改变的,我为什么不能做的事情一样X + = Y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆