当您在类内部使用时this,您引用的是当前实例:该类的实例。
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,指的是类的当前实例的this.firstName字段,并且(赋值的右侧部分)指的是构造函数范围中定义的变量。firstNamePersonfirstName
所以当你这样做时:
Person me = new Person("Oscar", "Mederos")
Run Code Online (Sandbox Code Playgroud)
this指实例Person实例me。
编辑:
Asthis指的是类实例,不能在静态类中使用。
this(也)用于在类中定义索引器a[0],例如在数组中: , a["John"],...