在 c# Visual studio 与 Stylecop 中使用此关键字

Using this keyword in c# Visual studio vs Stylecop

我正在开发一个 windows 服务 C# 项目,这是我第一次使用 C#。

对于同一个 this 关键字,我从 VS 和 Stylecop 收到了 2 条不同的建议。 (我知道,this关键字指的是class的当前实例)

所以我删除了这个关键字,我得到了 stylecop 的建议

SA1101 : CSharp.Readability : The call to serializeBackupFilePath must begin with the 'this.' prefix to indicate that the item is a member of the class.

所以,我在这里很困惑,那么有 this 关键字的构造函数和没有 this 关键字的构造函数之间会有什么区别吗? (抱歉我的英语不好)

我不想使用 this。但是,由于您对参数和 class 成员使用相同的命名约定,如果没有它,可能很难区分这两者。

由于您使用的是 C#,因此我建议您使用此命名约定,以避免您需要使用 this 来明确指定您的意思:

  • _name 私人 class 会员
  • Name for public class 成员、常量和方法名称
  • name 参数和局部变量

StyleCop 对 SA1101 的官方描述是:

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.

我完全不同意这一点,但也许它可以帮助您决定是否使用 this

顺便说一句:this has already been discussed StyleCop's Github
官方建议禁用SA1101.