c# 下面构造函数中的两个 this 关键字有什么区别?

标签 c# constructor this

我不明白以下内容: 在下面的代码中,Visual Studio 告诉我,我可以通过删除构造函数中的第二个 this 关键字来简化我的代码。

但为什么我不能去掉第一个 this 关键字呢? 这两个变量都是在构造函数之外的类中声明的,因此对于实例来说,这两个变量都将被“覆盖”*。

如果我删除了两个 this 关键字,那么 VS 会提示第一个赋值是对同一个变量进行的,但第二个不是。 对我来说唯一明显的区别是第二个变量是一个数组,但我不明白这会有什么不同?

*我怀疑覆盖在这里不是正确的术语。

public class CelestialObject {

    CelestialBody[] celestialBodies;
    int celestialBodyCount;

    public CelestialObject(int celestialBodyCount = 2) {
        this.celestialBodyCount = celestialBodyCount;
        this.celestialBodies = new CelestialBody[celestialBodyCount];
    }
}

最佳答案

您不能取消第一个 this 关键字,因为您有一个与字段 celestialBodyCount 同名的参数:

int celestialBodyCount; // The field

public CelestialObject(int celestialBodyCount = 2) { // The parameter.

this 关键字是必需的,以指示该字段被分配给。否则参数优先于字段,如 3.7.1 Name hiding 中所述。 :

... the scope of an entity may include declarations that introduce new declaration spaces containing entities of the same name. Such declarations cause the original entity to become hidden.

然后 3.7.1.1 Hiding through nesting :

Name hiding through nesting can occur as a result of nesting namespaces or types within namespaces, as a result of nesting types within classes or structs, and as a result of parameter and local variable declarations.

在这种情况下,参数 celestialBodyCount 隐藏了成员 celestialBodyCount

当然,如果您确实删除了this,编译器会给您以下警告:

Assignment made to same variable; did you mean to assign something else?

此警告几乎总是表示存在错误,应始终清除。

关于c# 下面构造函数中的两个 this 关键字有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411668/

相关文章:

c# - 当有单独的数据模型时,如何从存储库返回域对象?

c# - Windows 应用商店应用程序中的 TopAppBar 按钮 AutomationProperties 样式

c# - 如何将饼图添加到我的 winforms 应用程序?

javascript - 当我尝试创建 Javascript 对象时未捕获引用错误

javascript - TypeScript 中的“This”作用域

C# 泛型 - 类型参数的约束

C++构造函数调用另一个构造函数

javascript - 功能未被识别为功能?

javascript - 在 javascript 类中调用函数

jQuery 此选择器不可用于 animate() 方法属性