gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:03:25 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com