你应该总是用"this"来引用本地类变量吗?

gho*_*ost 5 c#

在C#中,您可以使用'this'关键字引用类中的值.

class MyClass
{
    private string foo;

    public string MyMethod()
    {
        return this.foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我认为答案可能是用户偏好,但最好在类中使用this关键字作为本地值吗?

Joh*_*lla 12

根据DRY的精神,我想说这不是一般特别有用的做法.this通过删除,几乎任何使用都可以缩短为等效表达式this.

一个例外是如果你有一个本地参数恰好与另一个类成员同名; 在这种情况下,你必须区分两者this.但是,只需重命名参数,就可以轻松避免这种情况.

  • 这是对DRY的误传.DRY指代代码重用,而不是为了节省一些键击而删除语法. (2认同)

CMS*_*CMS 5

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)