The so-called generics in C #: The use of parameterized types to manipulate multiple data types on the same code. Generic programming is a programming paradigm that uses "parameterized types" to abstract types to achieve more flexible reuse.
C # generics give code stronger type safety, better reuse, higher efficiency, and clearer constraints.
Introduction to C # generics mechanism
C # Generic capabilities are supported by the CLR at runtime, different from the compile-time template mechanism of C + +, and Java's compile-time "wiping" method. This allows generics to interoperate seamlessly between the various languages that support the CLR.
C # generic code, when compiled as IL and metadata, uses special placeholders to represent generic types, and supports generic operations with proprietary IL directives. The true generics instantiation works in a "on-demand" manner, which occurs at JIT-compilation time.
C # Generic compilation mechanism
At the first compile time, the compiler produces only "generic" IL Code and metadata for the stack type, does not instantiate the generic type, and T acts as a placeholder in the middle.
At JIT-compilation time, when the JIT compiler encounters a stack for the first time, the generic version IL Code and T in the metadata are substituted with the int type to instantiate the generic type.
The CLR produces the same code for a generic type with all type parameters of reference type, but if the type argument is a value type, the CLR generates a separate code for each of the different value types.
Several features of C # generics
If the parameters of the instantiated generic type are the same, the JIT compiler uses the type repeatedly, so the dynamic generics capability of C # avoids the problem of code bloat that can be caused by a C + + static template.
C # Generic types carry rich metadata, so the generic types of C # can be applied to powerful reflection techniques.
C # 's generics Adopt a "base class, interface, constructor, value type/reference type" constraint to implement the "display constraints" of the type parameters, improve the type security, but also lose the C + + template based on the "signature" implicit constraints have high flexibility.
C # generic classes and structs
Class c{}//Legal
Class d:c{}//Legal
Class e:c{}//Legal
Class f:c{}//Legal
Class g:c{}//illegal