的&QUOT含义;这与QUOT;一个结构(C#) [英] Meaning of "this" for a struct (C#)

查看:382
本文介绍了的&QUOT含义;这与QUOT;一个结构(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 an out parameter of the struct type, and within an instance function member of a struct, this corresponds to a ref 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 to this or by passing this as a ref or out 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 structs 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 structs obey value semantics and classes 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含义;这与QUOT;一个结构(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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