使用其对象(实例)访问类的私有成员变量 [英] Access private member variable of the class using its object (instance)

查看:125
本文介绍了使用其对象(实例)访问类的私有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是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

我认为我们无法使用该对象访问私有成员,但也许CLR允许我们这样做.因此,这意味着访问修饰符基于类型而不是该类型的实例.我也听说c ++也允许这样做.

有人猜想这可能是什么原因吗?

我认为RoBorg提供的msdn链接中的这一行解释了此行为 声明私有元素的类型中的代码,包括所包含类型中的代码,都可以访问该元素"

解决方案

您的问题相当令人困惑,但我认为我的理解是: 为什么我可以访问(我的班级的)另一个实例的私有变量?"

您是对的-在我使用过的所有OOP语言中,您都可以从其他实例访问私有变量,这恰恰是因为访问权限基于代码的位置,而不是代码所属于的对象实例. /p>

否则可能很难实现复制构造函数或相等运算符.

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 "

解决方案

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.

这篇关于使用其对象(实例)访问类的私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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