Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c# - can we access a private variable using an object

We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself. why??

class Program
{
    private int i;

    public void method1()
    {            
        Program p = new Program();
        p.i = 5;        // OK when accessed within the class
    }

}

class AnotherClass
{

    void method2()
    {
        Program p = new Program();
        p.i = 5; //error because private variables cannot be accessed with an object which is created out side the class
    }

}

Now I think every one got my point??

In both the cases above, we are accessing the private variable 'i' through the object 'p'. But inside class it is allowed, outside the class not allowed. Can anybody tell me the reason behind this??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can access i from within the class because private members can only be accessed by members of the class. In this case it looks strange because p is a different object than the object that accesses the variable, but its still the same class and the restriction is on the class level not on the object level.

class Program
{
    private int i;

    public void method1()
    {            
        Program p = new Program();
        p.i = 5;        // OK when accessed within the class
    }

}

You can not access i from within another class (unless it is an inner class but that's a different story). Which is completely as expected.

class AnotherClass
{
    void method2()
    {
        Program p = new Program();
        p.i = 5; //error because private variables cannot be accessed with an object which is created out side the class
    }
}

I understand the point you want to make. The restriction on class level looks counter intuitively. And maybe this is wrong. But the member variables are still only accessible from within the class, so you still have total control to guarantee the encapsulation of your privates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...