C# Properties and this-keyword

孤者浪人 提交于 2019-12-14 03:14:25

问题


When should I use the this-keyword for properties in code?

public class MyClass {
    public string MyString { get; private set; }
    public void MyMethod() {
        OtherClass.DoStuff(MyString); // Or this.MyString?
    }
}

I know that if the type and name of a property is the same you have to use this. to make it work.

public string Emailer Emailer { get { return _emailer; } }

What are the guidelines for using this. on Properties and even Methods in a class? I know it makes no difference in the compiled code. It's all about... hold your breath... best practices.


回答1:


Do whatever you and your team find most readable. Some people like to be explicit; I only specify this when I actually have to. It will make no difference to the compiled code.




回答2:


If a parameter name and an instance member have the same name, you will need to use this.

Like:

public class MyClass
{
    private string something;

    public void SomeMethod (string something)
    {
        this.something = something;
    }
}

But I'd advice you to choose names in that fashion that you'll never need to use this. Doing otherwise is just asking for trouble - sooner or later you'll forget this somewhere and will have a hard time debugging your code.




回答3:


Whether or not to use this is mostly an issue of preference and hence there is no right or wrong answer. It can become a bit of a religous war though with devs. I often find it's best to come to an agreement on the team one way or the other and use StyleCop to enforce the decision afterwards.

Personally I prefer brevity and only use this when it's actually necessary. But I'd choose code base consistency over my personal preferences here because it's a fairly minor issue.

There are a few cases where it's explicitly needed. Extension methods on this and in certain cases to disambiguate an identifier come to mind. I find these are fairly rare though.



来源:https://stackoverflow.com/questions/3564260/c-sharp-properties-and-this-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!