Access private member variable of the class using its object (instance)

无人久伴 提交于 2019-12-23 04:07:10

问题


Here is a VB.NET code snippet

Public Class OOPDemo

    Private _strtString as String

    Public Function Func(obj as OOPDemo) as boolean
      obj._strString = "I can set value to private member using a object"

    End Function

End Class

I thought we cannot access the private members using the object, but perhaps CLR allows us to do that. So that means that access modifiers are based on the type and not on the instance of that type. I have also heard that c++ also allows that..

Any guesses what could be the reason for this?

Edit:

I think this line from the msdn link given by RoBorg explains this behaviour "Code in the type that declares a private element, including code within contained types, can access the element "


回答1:


Your question is quite confusing but I think I've understood it as: "Why can I access another instance (of my class)'s private variables?"

And you're right - in all OOP languages I've used you can access private variables from other instances, precisely because access permissions are based on where the code is, rather than to which object instance it 'belongs'.

It might be hard to implement copy constructors or equality operators otherwise.




回答2:


Here's the section about access levels in MSDN.



来源:https://stackoverflow.com/questions/346127/access-private-member-variable-of-the-class-using-its-object-instance

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