C# 结构 "this = ...."

标签 c# struct

我刚刚在反射器中浏览了一个文件,并在结构构造函数中看到了这个:

this = new Binder.SyntaxNodeOrToken();

我以前从未见过该术语。有人能解释一下这个赋值在 C# 中的含义吗?谷歌很难。

最佳答案

它基本上取代了值(value)。它有效地将所有字段从右侧复制到左侧......除了即使字段是只读的,它也能工作。是的,它确实看起来很奇怪,而且有点吓人。

例子:

using System;

class Test
{
    static void Main()
    {
        Point point = new Point(10, 20);
        point.ReplaceWith(new Point(2, 3));
        Console.WriteLine(point); // (2, 3)
    }
}

struct Point
{
    private readonly int x;
    private readonly int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public void ReplaceWith(Point other)
    {
        this = other;
    }

    public override string ToString()
    {
        return string.Format("({0}, {1})", x, y);
    }
}

有关详细信息,请阅读 C# 4 规范的第 7.6.7 节,其中包括:

  • [text about its use in a struct constructor]

  • When this is used in a primary-expression within an instance method or instance accessor of a struct, it is classified as a variable. The type of the variable is the instance type of the struct within which the usage occurs.

    • If the method or accessor is not an iterator, the this variable represents the struct for which the method or accessor was invoked, and behaves exactly the same as a ref parameter of the struct type.

    • [text about iterators]

关于C# 结构 "this = ....",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9648939/

相关文章:

c# - 类 VS 引用结构

c - 将数据添加到从循环内的结构读取的数组中

c# - 生成 xml 文件和/或 html xml 注释的 html 文件

c# - 删除具有外键约束的 Access 记录

c# - 如何使用 syndicationFeed 从 rss 中读取图像 url?

c# - 如何在 Windows Phone 7 设备上拍摄位图图像并另存为 JPEG 图像文件?

c# - 在 linq 中,如何从列表中取出特定参数并构建不同类型的新列表?

C 结构信息隐藏(不透明指针)

c - 如果我有一个指向结构的指针,我如何访问它的成员之一?

pointers - Golang 编辑从 main() 到函数的 struts 数组