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 …