In .NET, Why Can I Access Private Members of a Class Instance within the Class?

陌路散爱 提交于 2019-12-05 05:11:00

This is "normal". Private members are private to the class, not to the particular instance.

You said:

Please explain, don't just tell me the rule.

Well, here's my two cents.

As I see it, the premise of private members of a class is that a class may internally be aware of its own implementation without exposing that implementation to the outside world. Thus one instance of a class is perfectly capable of understanding the way another instance of the same class is implemented; so it is not restricted from taking advantage of that implementation knowledge.

As for instances manipulating each other, I will concede this is somewhat unusual. But take for example static construction methods. Would you also restrict these from accessing instances' private members? If so, you've rendered a lot of useful code impossible. If not, it's unclear why static methods should be able to access private members but instance methods shouldn't.

In other words, the word "private" in OOP is not meant to convey the idea of personal privacy, as in individuals hiding from one another. Rather, think of a class as more of a "members only" sort of club, where there are certain ways of doing things that only members of the club know about.

The issue of access is about where the code is accessing the private members and not so much about what it is accessing them through.

You have access to the _foo._int field in the definition of the Foo class, but not outside of it.

It may surprise you further that the following extension to the nested Fred class is also legal.

Private Class Fred
    Private _int As Integer
    Private Sub Blah(ByVal foo As Foo)
        foo._int = 9
    End Sub
End Class

This is expected behavior. Nested classes can access private members of the container class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!