即使在所有者 class 中,也只能通过 属性 访问成员?

Make member only accessible through property even in owner class?

让我们看看这段代码:

class A {
    int m_x;
    public int x {
        get { return m_x; }
        set { ... }
    }
}

m_x 是私有的,因此可以在 class A 中访问,但其他 classes 只能通过 public x 属性.

我有一些方法必须在每次 x 改变时调用。 (在 set { ... } 中)

我的问题是在class A中我可以直接改变m_x的值。

目前这个错误的唯一指标是 m_ 前缀。

有没有办法进行编译时检查?

Is there a way to make a compile-time checking?

不,class A 应该知道它必须在每次设置私有字段时调用该方法。这是 class 实际实现的内部逻辑的一部分。

编译器无法阻止您在不先调用方法的情况下设置私有字段。这将是 class 的开发人员而不是编译器的责任。