Puzzle from an Interview with Eric Lippert: Inheritance and Generic Type Setting

前端 未结 5 597
我在风中等你
我在风中等你 2020-12-18 04:12

Can someone explain to me why the below code outputs what it does? Why is T a String in the first one, not an Int32, and why is it the opposite case in the next output?

5条回答
  •  眼角桃花
    2020-12-18 04:56

    Changing the code slightly:

    public class A
    {
        public class B : A
        {
            public void M() { System.Console.WriteLine(typeof(T)); }
            public class C : A.B { }
        }
    }
    
    public class P
    {
        public static void Main()
        {            
            (new A.B.C()).M(); //Outputs System.String
        }
    }
    

    Note how I changed C's base class from B to A.B. This changes the output from System.Int32 to System.String.

    Without that, A.B.C derives not from A.B, but from A.B, causing the behaviour you've seen. That's because in general, names defined in base classes are available by unqualified lookup, and the name B is defined in the base class A.

提交回复
热议问题