Private field accessible from another instance of the same class

I do not get the following. I always thought that I could only access private fields from the class in which the field was declared. However, in this case, I can 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?
        });
    }
}
+3
source share
5 answers

Technically, this is not a class Sessionthat accesses a private variable A; it delegates a function created in SendData()that does this. There is no problem with this. Think of it this way IterateClients- it's just a method of calling from a class clientthat can access a variable Asince it is in the same class.

0
source

The way it should work.

; this.

+5

, . .

:

class c1
{
        private int A;

        public void test(c1 c)
        {
        c.A = 5;

        }

}

Illegal:

class c2
{
  public void test(c1 c)
  {
     c.A = 5;
  }
}
+5

client. Session. ( " " ), client A.

+1

,

therefore, you will gain access to the private field from the class in which the private variable is declared. it is also allowed in Java.

0
source

All Articles