相关疑难解决方法(0)

为什么私有成员变量可以被类实例更改?

class TestClass
{
    private string _privateString = "hello";
    void ChangeData()
    {
        TestClass otherTestClass = new TestClass();
        otherTestClass._privateString = "world";
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码在C#中编译,并且在PHP中等效,但有人可以解释为什么otherTestClass._privateString可以在这里更改?

我认为类的实例在任何情况下都不应该能够更改私有成员变量,并且尝试访问otherTestClass._privateString会因"保护级别"错误而导致"无法访问".

但事实并非如此,那么为什么在自己的类中实例化一个对象可以让你访问私有成员呢?如果它,这不会破坏封装到一定程度?还是我错过了一些明显的东西?

  • (我不是在问上面的班级设计是不是很好的做法,只是想知道它背后的理论.)

Edit - Thanks for the answers and comments. To clarify, I'm also interested in knowing if being able to do this is regarded as a positive feature, or if it's a necessary tradeoff for better compile-time checking/code clarity/because most other languages do it that way or whatever. It seems to me …

c# oop encapsulation instantiation private-members

27
推荐指数
2
解决办法
2244
查看次数

标签 统计

c# ×1

encapsulation ×1

instantiation ×1

oop ×1

private-members ×1