我目前正在尝试了解 '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/