可从同一类的另一个实例访问私有字段
我没有得到以下信息..我一直认为我只能从声明该字段的类访问私有字段。但是在这种情况下我可以访问它:
class Session
{
List<client> ListOfClients = new List<client>();
public void IterateClients(Action<client> action)
{
}
}
class client
{
private int A;
Session area;
public void SendData()
{
area.IterateClients(delegate(client c)
{
c.A = 5; //how come this is accessible?
});
}
}
I do not get the following..I always thought I can access private fields only from class which the field was declared in. However in this case I am able to access it:
class Session
{
List<client> ListOfClients = new List<client>();
public void IterateClients(Action<client> action)
{
}
}
class client
{
private int A;
Session area;
public void SendData()
{
area.IterateClients(delegate(client c)
{
c.A = 5; //how come this is accessible?
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只能从它所属的类访问私有数据。同一类的两个对象可以访问彼此的私有部分。
合法:
非法:
You can only access private data from the CLASS it is a member of. Two objects of the same class can access each other's private parts.
Legal:
Illegal:
这就是它应该工作的方式。
你的理解不正确;私有成员不限于
this
限定符。That's the way it's supposed to work.
Your understanding was incorrect; private members are not limited to the
this
qualifier.你是对的
因此您要从声明私有变量的类访问私有字段。这在 Java 中也是允许的。
you are right
so u're accessing the private field from the class in which which the private variable is declared. this is allowed in Java too.
client
类中有一个方法。在此方法中,您调用Session
类的方法。在此调用中,您有一个委托(一种“回调”),该委托在类client
的上下文中运行,因此可以访问私有成员A
。You have a method inside class
client
. In this method you give a call to a method of classSession
. In this call you have a delegate (a kind of "callback"), this delegate runs in the context of classclient
and therefore can access private memberA
.从技术上讲,访问私有
A
变量的不是Session
类,而是在SendData()
中创建的委托函数来执行此操作。这没有问题。可以将其视为IterateClients
只是从client
类调用方法,该方法可以访问A
变量,因为它位于同一个类中。Technically it's not
Session
class that's accessing privateA
variable, it's delegate function created inSendData()
that does this. There is no problem with that. Think of it asIterateClients
is just calling method fromclient
class, which method can accessA
variable since it is on the same class.