使用下面定义的类,我希望我需要通过在它们前面加上'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)
因为没有冲突的本地范围的描述变量,在这种情况下使用类型或实例成员.
优先顺序
因此,如果您有一个也命名的局部变量,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)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |