简体   繁体   English

为什么可以通过这种方式访问​​私有变量时无法访问基类的私有字段

[英]Why I can not access private field of a base class when private variables can be accessed this way

I was reading question mentioned at links below 我正在阅读以下链接中提到的问题
Why are private fields private to the type, not the instance? 为什么专用字段专用于类型而不是实例专用?
Access to private members of class 访问班级的私人成员
Access private field of a instance object 访问实例对象的私有字段

public class MyClass : ClassA
    {
        private object myObj;

        public object Field
        {
            get { return myObj; }
            set { myObj = value; }
        }

        public MyClass()
        { 
        }


        public MyClass(MyClass class1)
        {
            class1.myObj = 5;
            this.myObj = class1.myObj;
            class1.myObjOfClassA; // Why I can not access myObjOfClassA when I can access myObj of class1 object
        }
    }


    public class ClassA
    {
        private object myObjOfClassA;

    }

My question is 我的问题是
1) If we can access the private variables of Class as mentioned then why a class which extends another class can not access private variables of base class? 1)如果我们可以如上所述访问类的私有变量,那么为什么扩展了另一个类的类不能访问基类的私有变量?

2) I believe when code or classes will be compiled then all the methods, variables etc of base class will be added to derived class. 2)我相信当代码或类将被编译时,所有基类的方法,变量等都将被添加到派生类中。 Am I right on this? 我说得对吗?

If we can access the private variables of Class as mentioned then why a class which extends another class can not access private variables of base class? 如果我们可以如上所述访问类的私有变量,那么为什么扩展另一个类的类不能访问基类的私有变量?

Because the variable isn't declared in the program text of the derived class, which is how private access is defined for Java and C#. 因为该变量未在派生类的程序文本中声明,所以这是为Java和C#定义私有访问的方式。 (The details around nested classes vary between Java and C#; if you want details for one language or the other, please be more specific in your question.) (关于嵌套类的详细信息在Java和C#之间有所不同;如果您想要一种或多种语言的详细信息,请在问题中更具体地说明。)

I believe when code or classes will be compiled then all the methods, variables etc of base class will be added to derived class. 我相信,当将编译代码或类时,基类的所有方法,变量等都将添加到派生类中。 Am I right on this? 我说得对吗?

They're not added to the class, no. 他们没有添加到班级,不。 They're inherited by the derived class, and any instance of the derived class will have all the fields that are inherited - but that's not the same as them behaving as if they were declared in the derived class. 它们是由派生类继承的,派生类的任何实例都将具有所有被继承的字段-但这与它们在派生类中声明时的行为不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM