本文介绍了C# 结构体“this = ...."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've just been browsing a file in reflector and seen this in a struct constructor:

this = new Binder.SyntaxNodeOrToken();

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

I've not seen that terminology before. Can someone explain what that this assignment means in C#. It's difficult to Google.

推荐答案

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

It replaces the value, basically. It effectively copies all the fields from the right side to the left... except it works even if the fields are readonly. And yes, it does look distinctly weird, and it's somewhat scary.

示例:

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 节,其中包括:

For more information, read section 7.6.7 of the C# 4 spec, which includes:

  • [关于它在结构构造函数中使用的文本]

this 用于结构的实例方法或实例访问器中的primary-expression 时,它被归类为变量.变量的类型是发生用法的结构体的实例类型.

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.

  • 如果方法或访问器不是迭代器,this 变量表示调用方法或访问器的结构,其行为与 ref struct 类型的参数.

  • 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.

[关于迭代器的文字]

这篇关于C# 结构体“this = ...."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:39