C#泛型如何工作?

How C# generic works?

C++ 模板在编译时生成。我听说 C# 泛型是在运行时生成的。这意味着它是在 IL -> 执行时生成的?这部分也包含在runtime中吗?

您的断言是正确的,C++ 模板完全在编译时构建,.Net 在 运行 时创建它需要的类型。虽然,泛型类型需要在编译时解决,但是为 MSIL 生成的 类 被使用和重用是在 运行 时生成的(尽管略微值类型和引用类型不同)

Differences Between C++ Templates and C# Generics (C# Programming Guide)

C# Generics and C++ templates are both language features that provide support for parameterized types. However, there are many differences between the two. At the syntax level, C# generics are a simpler approach to parameterized types without the complexity of C++ templates. In addition, C# does not attempt to provide all of the functionality that C++ templates provide. At the implementation level, the primary difference is that C# generic type substitutions are performed at runtime and generic type information is thereby preserved for instantiated objects.

Generics in the Run Time (C# Programming Guide)

值类型

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.

引用类型

Generics work somewhat differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with object references substituted for the parameters in the MSIL. Then, every time that a constructed type is instantiated with a reference type as its parameter, regardless of what type it is, the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size.