69

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?

4

9 回答 9

94

I don't really follow this guidance unless I'm in the scenarios you need it:

  • there is an actual ambiguity - mainly this impacts either constructors (this.name = name;) or things like Equals (return this.id == other.id;)
  • you want to pass a reference to the current instance
  • you want to call an extension method on the current instance

Other than that I consider this clutter. So I turn the rule off.

于 2009-10-13T19:56:32.547 回答
70

It can make code clearer at a glance. When you use this, it's easier to:

  • Tell static and instance members apart. (And distinguish instance methods from delegates.)
  • Distinguish instance members from local variables and parameters (without using a naming convention).
于 2009-10-13T19:51:06.147 回答
39

I think this article explains it a little

http://blogs.msdn.microsoft.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx

...a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.

于 2009-10-13T19:57:39.717 回答
23
this.This 
this.Does 
this.Not 
this.Add 
this.Clarity 
this.Nor 
this.Does 
this.This 
this.Add 
this.Maintainability 
this.To 
this.Code

The usage of "this.", when used excessively or a forced style requirement, is nothing more then a contrivance used under the guise that there is < 1% of developers that really do not understand code or what they are doing, and makes it painful for 99% who want to write easily readable and maintainable code.

As soon as you start typing, Intellisence will list the content available in the scope of where you are typing, "this." is not necessary to expose class members, and unless you are completely clueless to what you are coding for you should be able to easily find the item you need.

Even if you are completely clueless, use "this." to hint what is available, but don't leave it in code. There are also a slew of add-ons like Resharper that help to bring clarity to the scope and expose the contents of objects more efficiently. It is better to learn how to use the tools provided to you then to develop a bad habit that is hated by a large number of your co-workers.

Any developer that does not inherently understand the scope of static, local, class or global content should not rely on "hints" to indicate the scope. "this." is worse then Hungarian notation as at least Hungarian notation provided an idea about the type the variable is referencing and serves some benefit. I would rather see "_" or "m" used to denote class field members then to see "this." everywhere.

I have never had an issue, nor seen an issue with a fellow developer that repeatedly fights with code scope or writes code that is always buggy because of not using "this." explicitly. It is an unwarranted fear that "this." prevents future code bugs and is often the argument used where ignorance is valued.

Coders grow with experience, "this." is like asking someone to put training wheels on their bike as an adult because it is what they first had to use to learn how to ride a bike. And adult might fall off a bike 1 in 1,000 times they get on it, but that is no reason to force them to use training wheels.

"this." should be banned from the language definition for C#, unfortunately there is only one reason for using it, and that is to resolve ambiguity, which could also be easily resolved through better code practices.

于 2014-06-10T16:05:19.290 回答
10

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.

于 2009-10-13T20:06:25.533 回答
9

A few basic reasons for using this (and I coincidentally always prefix class values with the name of the class of which they are a part as well - even within the class itself).

1) Clarity. You know right this instant which variables you declared in the class definition and which you declared as locals, parameters and whatnot. In two years, you won't know that and you'll go on a wondrous voyage of re-discovery that is absolutely pointless and not required if you specifically state the parent up front. Somebody else working on your code has no idea from the get-go and thus benefits instantly.

2) Intellisense. If you type 'this.' you get all instance-specific members and properties in the help. It makes finding things a lot easier, especially if you're maintaining somebody else's code or code you haven't looked at in a couple of years. It also helps you avoid errors caused by misconceptions of what variables and methods are declared where and how. It can help you discover errors that otherwise wouldn't show up until the compiler choked on your code.

3) Granted you can achieve the same effect by using prefixes and other techniques, but this begs the question of why you would invent a mechanism to handle a problem when there is a mechanism to do so built into the language that is actually supported by the IDE? If you touch-type, even in part, it will ultimately reduce your error rate, too, by not forcing you to take your fingers out of the home position to get to the underscore key.

I see lots of young programmers who make a big deal out of the time they will save by not typing a character or two. Most of your time will be spent debugging, not coding. Don't worry so much about your typing speed. Worry more about how quickly you can understand what is going on in the code. If you save a total of five minutes coding and win up spending an extra ten minutes debugging, you've slowed yourself down, no matter how fast you look like you're going.

于 2013-06-29T22:24:38.933 回答
4

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.

于 2009-10-13T19:53:49.613 回答
3

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; 
  }
}
于 2009-10-13T19:55:36.880 回答
1

I follow it mainly for intellisense reasons. It is so nice typing this. and getting a consise list of properties, methods, etc.

于 2010-02-24T01:40:14.787 回答