的"含义;这与QUOT;一个结构(C#) [英] Meaning of "this" for a struct (C#)
问题描述
根据MSDN(中的 C#规格):
According to MSDN (Section 11.3.6 of the C# spec):
在一个
的实例构造函数结构,这个
对应于结构类型的退出
参数,以及内
A结构的实例函数成员,结构类型的这种
相当于 REF
参数。在这两个
的情况下,此
被归类为
可变的,并且有可能修改
中的整个结构的量,
函数成员是由
调用分配给这个
或者通过这个
作为 REF
或退出
参数。
Within an instance constructor of a struct,
this
corresponds to anout
parameter of the struct type, and within an instance function member of a struct,this
corresponds to aref
parameter of the struct type. In both cases,this
is classified as a variable, and it is possible to modify the entire struct for which the function member was invoked by assigning tothis
or by passingthis
as aref
orout
parameter.
我不明白这一点。如何为这个
的结构比一类的有什么不同?代码示例是值得赞赏的。
I don't get it. How is this
different for a struct than for a class? Code examples are appreciated
推荐答案
埃里克利珀有一个神话般的帖子 只读结构
SA而回,这将真正帮助澄清这一问题为你。甚至还有一个代码示例,以及一个小测验!
Eric Lippert had a fabulous post on mutating readonly struct
s a while back that will really help clarify the issue for you. There's even a code example, and a quiz!
最关键的一点是,结构
取值服从值语义和类
ES不要等这个
必须算数两个不同的。 这个
是只读
为类
,而不是一个结构
。下面的代码是合法的。
The salient point is that struct
s obey value semantics and class
es do not and so this
must mean something different for the two. this
is readonly
for a class
, but not for a struct
. The following code is legal
struct Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void DoGoTime() {
GoTime(ref this);
}
public static void GoTime(ref Point p) {
p.x = 100;
p.y = 100;
}
}
但没有如果结构
被替换为类
这篇关于的"含义;这与QUOT;一个结构(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!