简体   繁体   English

从孩子班级的孩子取得家长成员

[英]Accessing parent member from child of child class

Today I faced a very odd interview question. 今天,我面临一个非常奇怪的面试问题。 The interviewer asked me:- 面试官问我:

There is a class Parent and it has a method GetData . 有一个Parent类,它有一个GetData方法。 Class Child1 inherits Parent and Child2 inherits Child1. Child1类继承Parent1,Child2继承Child1。 What you can do in Parent class so that the method "GetData" will be accessible from Child1 but not from Child2? 您可以在Parent类中做什么,以便可以从Child1而不是Child2访问方法“ GetData”?

Kind of a weird setup, but here's another option that works because nested classes can access private members of the outer class: 有点奇怪的设置,但是这是另一个可行的选择,因为嵌套类可以访问外部类的私有成员:

public class Parent
{
    public Parent()
    {
        GetData();
    }

    private void GetData()
    {
    }        

    public class Child1 : Parent
    {
        public Child1()
        {
            GetData();
        }
    }

}

class Child2 : Parent.Child1
{
    public Child2()
    {
        GetData(); //compiler error, inaccessible due to protection level
    }
}

Parent class can mark it's method as private, then declare the first Child inside of it's own declaration. 父类可以将其方法标记为私有,然后在其自己的声明中声明第一个Child。

    public class Job
    {

        private void Test()
        {

        }

        public class JobChild : Job
        {
            public JobChild()
            {
                //works
                this.Test();
            }

        }
    }


    public class JobChildTwo : Job.JobChild
    {
        public JobChildTwo()
        {
            //doesn't work
            this.Test();
        }
    }

If we assume that Parent and Child1 exist in Assembly A while Child2 exists in Assembly B, and Assembly A does not expose its internals to Assembly B whilst Assembly B references Assembly A, then you can mark GetData as internal, at which point it will be accessible to Child1 but not Child2. 如果我们假设在装配A中存在Parent和Child1,而在装配B中存在Child2,并且装配A在装配B引用装配A时不向装配B公开其内部,那么您可以将GetData标记为内部,这时它将是Child1可以访问,Child2不能访问。

The side effect here is that it would be visible to the entire assembly. 这里的副作用是整个组件都可以看到它。

Note that protected internal would have the opposite effect - it would make GetData visible to child2, since protected internal is explicitly "protected OR internal" as per MSDN 请注意,受保护的内部将产生相反的效果-因为MSDN明确指出,受保护的内部是“受保护的或内部的”,所以child2可以看到GetData。

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

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