Why does field declaration with duplicated nested type in generic class results in huge source code increase?

后端 未结 3 1487
后悔当初
后悔当初 2021-01-30 16:53

Scenario is very rare, but quite simple: you define a generic class, then create a nested class which inherits from outer class and define a associative field (of self type) wit

3条回答
  •  情书的邮戳
    2021-01-30 17:24

    The core of your question is why Inner.Inner is a different type than Inner. Once you understand that, your observations about compile time and generated IL code size follow easily.

    The first thing to note is that when you have this declaration

    public class X
    {
      public class Y { }
    }
    

    There are infinitely many types associated with the name Y. There is one for each generic type argument T, so X.Y is different than X.Y, and, important for later, X>.Y is a different type than X.Y for all T's. You can test this for various types T.

    The next thing to note is that in

    public class A
    {
      public class B : A { }
    }
    

    There are infinitely many ways to refer to nested type B. One is A.B, another is A.B.B, and so on. The statement typeof(A.B) == typeof(A.B.B) returns true.

    When you combine these two, the way you have done, something interesting happens. The type Outer.Inner is not the same type as Outer.Inner.Inner. Outer.Inner is a subclass of Outer.Inner> while Outer.Inner.Inner is a subclass of Outer.Inner>.Inner>, which we established before as being different from Outer.Inner. So Outer.Inner.Inner and Outer.Inner are referring to different types.

    When generating IL, the compiler always uses fully qualified names for types. You have cleverly found a way to refer to types with names whose lengths that grow at exponential rates. That is why as you increase the generic arity of Outer or add additional levels .Y to the field field in Inner the output IL size and compile time grow so quickly.

    提交回复
    热议问题