C#结构体"这= ...." [英] C# Structs "this = ...."

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

问题描述

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

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:


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

  • [text about its use in a struct constructor]

这个是在初级前pression 的一个结构的实例方法或实例访问内使用,它被归类为一个变量。变量类型是在其中使用发生结构的实例类型。

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.


      
  • 如果方法或访问不是一个迭代器,在这个变量重新presents为其调用方法或访问器的结构和行为完全一样的 REF 参数的结构类型的。

  • 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#结构体"这= ...."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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