在C#中,您可以使用'this'关键字引用类中的值.
class MyClass
{
private string foo;
public string MyMethod()
{
return this.foo;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我认为答案可能是用户偏好,但最好在类中使用this关键字作为本地值吗?
我this几乎仅在某个成员隐藏另一个成员时,以及当我需要将当前类实例传递给方法时才使用该关键字,例如:
class Employee
{
private string name;
private string address;
// Pass the current object instance to another class:
public decimal Salary
{
get { return SalaryInfo.CalculateSalary(this); }
}
public Employee(string name, string address)
{
// Inside this constructor, the name and address private fields
// are hidden by the paramters...
this.name = name;
this.address = address;
}
}
Run Code Online (Sandbox Code Playgroud)