这真的是简化吗?

Jam*_*ood 22 c# visual-studio-2015

所以我有一个非常简单的带有Id字段的类,Id可以在构造函数中设置.

通常,我将使用它this来清楚地标识类属性而不是方法参数.对我来说,这似乎更清晰.

IDE0003要我删除this"姓名可以简化"的消息,这是正确的吗?

这对我来说似乎不太清楚,并且还容易导致套管错误id = id.

在此输入图像描述

mad*_*xej 36

另一个问题的答案是,您可以配置编辑器以删除行为.我个人喜欢"这个"

Tools > Options > Text Editor > C# > Code Style and check Qualify member access with 'this'
Run Code Online (Sandbox Code Playgroud)

Visual Studio 2015 - 更改灯泡,快速操作设置

  • 使用关键字"this"可以明确显示变量的存在位置.如果它没有前缀`this`,`base`或类的名称(对于静态方法),则变量的范围是本地的,并且作为方法是全局的.这使得意图和可读性比其遗漏更清楚. (9认同)

Cod*_*ter 9

this几乎总是关键字是不必要的,看你什么时候使用"this"关键字?.

允许容易导致套管错误 id = id

这将产生另一个警告:

对同一变量进行的赋值; 你的意思是分配其他东西吗?

  • C#区分大小写.在这种情况下,删除它确实是一种简化. (3认同)
  • @DieterB,如果C#区分大小写(照原样),那么实际上的简化是删除`this`而不是`This`:p (2认同)

Sal*_*ari 5

If you use General Naming Conventions then the this keyword is redundant because the parameter should be id and the property should be Id based on Naming Guidelines. So it seems clear:

public int Id 
{ 
   get; 
   private set; 
}


public VSOMessage(int id)
{
    Id = id;
}
Run Code Online (Sandbox Code Playgroud)

Please note that the guidelines itself don't say, to use or not use this keyword but because C# is case sensitive, it would be a simplification to remove this keyword but when you don't use Naming Conventions then you may naming the property id instead ofId so you should use this keyword in such cases.

  • 关键字[`this`](https://msdn.microsoft.com/zh-cn/library/dk1507sz.aspx)在这种情况下特别有用:“要限定由相似名称隐藏的成员”。此外,并非每个成员变量都是一个属性,某些属性可能具有后备变量(尤其对于不可变对象很有用)。另外,将`this`,`base`和类名用于静态方法可以提高可读性并巩固意图。 (4认同)