Here is a VB.NET code snippet
这是一个VB.NET代码片段
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..
我以为我们无法使用该对象访问私有成员,但也许CLR允许我们这样做。这意味着访问修饰符基于类型而不是该类型的实例。我也听说c ++也允许..
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 "
我认为来自RoBorg给出的msdn链接的这一行解释了这种行为“声明私有元素的类型中的代码,包括包含类型中的代码,可以访问该元素”
2 个解决方案
#1
3
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'.
你是对的 - 在我使用的所有OOP语言中,你可以从其他实例访问私有变量,正是因为访问权限是基于代码的位置,而不是它所属的对象实例。
It might be hard to implement copy constructors or equality operators otherwise.
否则可能很难实现复制构造函数或相等运算符。
#1
3
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'.
你是对的 - 在我使用的所有OOP语言中,你可以从其他实例访问私有变量,正是因为访问权限是基于代码的位置,而不是它所属的对象实例。
It might be hard to implement copy constructors or equality operators otherwise.
否则可能很难实现复制构造函数或相等运算符。