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

前端 未结 5 601
我在风中等你
我在风中等你 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:57

    Method M inside B prints typeof(T) of A, A is parent class of B.

    So irrespective of whether B is derived from whatever, M prints typeof(T) that is String.

    So A.B.M prints nearest A's T.

    So A.B.M will print string

    Now, let us expand expression A.B.C, which is equivalent to A.B.A.B (since C is A.B), so method A.B.A.B.M will print nearest T.

    A.B.A.B.M will print int

提交回复
热议问题