问题
I am working on a windows service C# project and I am working first time in C#.
An I am getting 2 different suggestion from VS as well Stylecop for a same this
keyword. (I know, this
keyword refers to the current instance of the class)
So I removed this keyword, and I am getting stylecop suggestion as
SA1101 : CSharp.Readability : The call to serializeBackupFilePath must begin with the 'this.' prefix to indicate that the item is a member of the class.
So, I am confused here, so is there will have any difference between constructor having this
keyword and constructor without this
keyword
(Sorry for my bad english)
回答1:
I prefer not using this
. However, since you are using the same naming convention for arguments and class members, it might be hard to differentiate between those two without it.
Since you are using C# I'd recommend this naming convention to avoid cases where you need to use this
to explicitly specify which one you mean:
_name
for private class membersName
for public class members, constants and method namesname
for arguments and local variables
StyleCop's official description for SA1101
is:
A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’. An exception to this rule occurs when there is a local override of a base class member, and the code intends to call the base class member directly, bypassing the local override. In this case the call can be prefixed with ‘base.’ rather than ‘this.’.
By default, StyleCop disallows the use of underscores or m_ to mark local class fields, in favor of the ‘this.’ prefix. The advantage of using ‘this.’ is that it applies equally to all element types including methods, properties, etc., and not just fields, making all calls to class members instantly recognizable, regardless of which editor is being used to view the code. Another advantage is that it creates a quick, recognizable differentiation between instance members and static members, which are not be prefixed.
A final advantage of using the ‘this.’ prefix is that typing this. will cause Visual Studio to show the IntelliSense popup, making it quick and easy for the developer to choose the class member to call.
I disagree completely with that, but maybe it helps you decide wether to use this
or not.
Btw: this has already been discussed StyleCop's Github.
The official recommendation is to disable SA1101
.
来源:https://stackoverflow.com/questions/37384224/using-this-keyword-in-c-sharp-visual-studio-vs-stylecop