c# - .NET 文档中 'this' 关键字的定义

标签 c# constructor this

我目前正在尝试了解 'this' 关键字,在 .NET 文档中是:

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

我通过“this”关键字学到的第一件事是,当类数据字段与构造函数中的示例参数具有相同名称时,如何解决范围歧义。像这样:

class Person
{
    public string name;

    public Person(string name)
    {
        this.name = name;
    }
}

这里使用“this”关键字来通知 C# 编译器我想要使用名为“name”的变量,并且它应该来自当前类实例范围而不是来自方法范围。例如,如果我在托管堆上创建 Person 类的对象,并引用我分配给名为“p1”的变量的该对象,则语句“this.name”实际上是“p1.X”(我知道我无法将其写入代码像这样,但只是为了更好的想象力)。如果确实如此,那么 .NET 文档中的定义对我来说对于这个示例来说是有意义的。

但是如果我使用“this”关键字来链接构造函数会怎么样?

我再次知道它的作用,但我真的不知道当前类实例中的“this”关键字使用什么?在第一个具有范围模糊性的示例中,这是有道理的,但在链接构造函数中,我真的不知道它与任何类实例有什么关系,因为它不使用实例中的任何内容,它只是将传入参数传递给主实例构造函数。

链接构造函数的示例:

class Person
{
    public string name;
    public int? age;

    public Person(string name): this(name, null) { }

    public Person(string initName, int? initAge)
    {
        name = initName;
        age = initAge;
    }
}

所以我的问题是,因为在文档中是这样写的,这个关键字指的是该类的当前实例: 当您将其与链接构造函数一起使用时,“this”关键字从类的当前实例引用什么?

谢谢各位的解答

最佳答案

What 'this' keyword is referring from current instance of the class when you use it with chaining constructors?

它指的是来自this类的构造函数调用(与来自类的构造函数相比)。

关于c# - .NET 文档中 'this' 关键字的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45040068/

相关文章:

java - 签名重叠时如何重载构造函数?

javascript - 为什么在调用 foo.fn() 时 JS 不总是将 `this` 绑定(bind)到 `foo`?

javascript - 如何选择 'this' onclick?

c# - 正确使用这个。在类构造函数中

c# - 减少相似对象的内存

c# - 如何从 Razor View 中调用带有可选参数的辅助方法?

c# - MVC 4 @HTML.HiddenFor 没有在回发时更新

Java 构造函数初始化?

c# - 我可以通过 Lucene 在 Orchard 中搜索/索引自定义数据源吗?

c++ - 标准 12.1 p14 中的 "unspecified value"是什么意思?