为什么Visual Studio会提示我不要将`this`关键字用于实例变量?

Zac*_*ith 2 c# this

使用下面定义的类,我希望我需要通过在它们前面加上'this'来显式声明实例变量.来自Ruby和Javascript背景,我期望description需要this在声明中加上前缀,并且在构造函数中需要前缀this.

为什么不需要?我假设description仍然是作为实例变量创建的?

public class Item
{
    private string description;
    public Item(string str)
    {
        this.description = str; // VS says the 'this' keyword can be omitted
    }
}
Run Code Online (Sandbox Code Playgroud)

Igo*_*gor 5

因为没有冲突的本地范围的描述变量,在这种情况下使用类型或实例成员.

优先顺序

  1. 局部变量
  2. 实例成员
  3. 键入(静态)成员

因此,如果您有一个也命名的局部变量,description但是您想要引用实例成员,那么this将是必需的,否则您将始终引用局部变量.

这是一个你应该使用的例子 this

public class Item
{
    private string description;
    public void SetDescription(string description)
    {
        this.description = description; // without this you would just be setting the local variable to itself
    }
}
Run Code Online (Sandbox Code Playgroud)