简体   繁体   中英

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 . Class Child1 inherits Parent and Child2 inherits Child1. What you can do in Parent class so that the method "GetData" will be accessible from Child1 but not from Child2?

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.

    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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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