Why does StyleCop recommend prefixing method or pr

2019-01-05 01:45发布

I have been trying to follow StyleCop's guidelines on a project, to see if the resulting code was better in the end. Most rules are reasonable or a matter of opinion on coding standard, but there is one rule which puzzles me, because I haven't seen anyone else recommend it, and because I don't see a clear benefit to it:

SA1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.

On the downside, the code is clearly more verbose that way, so what are the benefits of following that rule? Does anyone here follow that rule?

9条回答
倾城 Initia
2楼-- · 2019-01-05 02:15

In addition it is possible to duplicate variable names in a function so using 'this' can make it clearer.

class foo {
  private string aString;

  public void SetString(string aString){
    //this.aString refers to the class field
    //aString refers to the method parameter        
    this.aString = aString; 
  }
}
查看更多
爷、活的狠高调
3楼-- · 2019-01-05 02:20

Note that the compiler doesn't care whether you prefix references with this or not (unless there's a name collision with a local variable and a field or you want to call an extension method on the current instance.)

It's up to your style. Personally I remove this. from code as I think it decreases the signal to noise ratio.

Just because Microsoft uses this style internally doesn't mean you have to. StyleCop seems to be a MS-internal tool gone public. I'm all for adhering to the Microsoft conventions around public things, such as:

  • type names are in PascalCase
  • parameter names are in camelCase
  • interfaces should be prefixed with the letter I
  • use singular names for enums, except for when they're [Flags]

...but what happens in the private realms of your code is, well, private. Do whatever your team agrees upon.

Consistency is also important. It reduces cognitive load when reading code, especially if the code style is as you expect it. But even when dealing with a foreign coding style, if it's consistent then it won't take long to become used to it. Use tools like ReSharper and StyleCop to ensure consistency where you think it's important.

Using .NET Reflector suggests that Microsoft isn't that great at adhering to the StyleCop coding standards in the BCL anyway.

查看更多
forever°为你锁心
4楼-- · 2019-01-05 02:20

I do follow it, because I think it's really convenient to be able to tell apart access to static and instance members at first glance.

And of course I have to use it in my constructors, because I normally give the constructor parameters the same names as the field their values get assigned to. So I need "this" to access the fields.

查看更多
登录 后发表回答