为什么私有成员变量由类实例是否会改变? [英] Why can private member variable be changed by class instance?

查看:222
本文介绍了为什么私有成员变量由类实例是否会改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class TestClass
{
    private string _privateString = "hello";
    void ChangeData()
    {
        TestClass otherTestClass = new TestClass();
        otherTestClass._privateString = "world";
    }
}

这code编译C#和PHP中的等值的作品,但有人可以解释为什么 otherTestClass._privateString 可以在这里改变的原因吗?

This code compiles in C# and the equivalent works in PHP, but can someone explain the reason why otherTestClass._privateString can be changed here ?

我本来以为一个类的实例,不应该是能够改变在任何情况下一个私有成员变量,而试图访问 otherTestClass._privateString 将给出一个交通不便,由于保护级别的错误。

I would have thought an instance of a class should not be able to change a private member variable under any circumstances, and that trying to access otherTestClass._privateString would give an 'inaccessible due to protection level' error.

这是不是这样的,所以为什么实例化自己的类内的对象允许您访问私有成员?而且它应该,没有这个破封装到一个程度?还是我失去了一些东西明显?

This is not the case though, so why does instantiating an object inside its own class let you access the private members ? And should it, doesn't this break encapsulation to an extent ? Or am I missing something obvious ?


  • (我不要求如果上述一流的设计是很好的做法,只是不知道它背后的理论。)

修改 - 感谢您的答案和评论。为了澄清,我也想知道如果能够做到这被看作是一个积极的功能,或者如果是为了更好的编译时的必要权衡检查/ code清晰度/因为大多数其他语言那样做管他呢。在我看来,理想情况下,编译器将prevent或就此发出警告,但后来我根本不是一个语言设计者。 (在不违反封装),否则将很难或不可能的它是这样怎么可以让你做一些有益的任何例子将是巨大的。

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 ideally the compiler would prevent or warn you about this, but then I'm far from a language designer. Any examples of how it being this way lets you do something useful (without violating encapsulation) that would otherwise be difficult or impossible would be great.

推荐答案

私有成员对该类的程序文本中的任何code访问(包括嵌套类型内)。它无关,与你处理了该类的实例。

Private members are accessible to any code within the program text of that class (including within nested types). It has nothing to do with which instance of the class you're dealing with.

我不相信这违反了封装 - 该API仍然是从实现分离,但执行知道本身,无论哪个实例它望着

I don't believe this violates encapsulation - the API is still separated from the implementation, but the implementation "knows" about itself regardless of which instance it's looking at.

我相信,在其他一些语言中,这的不是的可访问性是如何工作的,但它绝对是C#和Java。 (Jav​​a有什么可以访问私有成员略有不同的规则,但翻译code为你写的仍然工作。)

I believe that in some other languages this isn't how accessibility works, but it definitely is for C# and Java. (Java has slightly different rules about what can access private members, but the translated code for what you've written would still work.)

这篇关于为什么私有成员变量由类实例是否会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆