Where are generic methods stored?

前端 未结 3 687
独厮守ぢ
独厮守ぢ 2020-12-07 22:19

I\'ve read some information about generics in .ΝΕΤ and noticed one interesting thing.

For example, if I have a generic class:

class Foo 
{ 
         


        
3条回答
  •  我在风中等你
    2020-12-07 22:40

    As opposed to C++ templates, .NET generics are evaluated in runtime, not at compile-time. Semantically, if you instantiate the generic class with different type parameters, those will behave as if it were two different classes, but under the hood, there is only one class in the compiled IL (intermediate language) code.

    Generic types

    The difference between different instantiatons of the same generic type becomes apparent when you use Reflection: typeof(YourClass) will not be the same as typeof(YourClass). These are called constructed generic types. There also exists a typeof(YourClass<>) which represents the generic type definition. Here are some further tips on dealing with generics via Reflection.

    When you instantiate a constructed generic class, the runtime generates a specialized class on the fly. There are subtle differences between how it works with value and reference types.

    • The compiler will only generate a single generic type into the assembly.
    • The runtime creates a separate version of your generic class for each value type you use it with.
    • The runtime allocates a separate set of static fields for each type parameter of the generic class.
    • Because reference types have the same size, the runtime can reuse the specialized version it generated the first time you used it with a reference type.

    Generic methods

    For generic methods, the principles are the same.

    • The compiler only generates one generic method, which is the generic method definition.
    • In runtime, each different specialization of the method is treated as a different method of the same class.

提交回复
热议问题