且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时构建c#泛型类型定义

更新时间:2022-12-30 15:33:28

MakeGenericType -即

Type passInType = ... /// perhaps myAssembly.GetType(
        "ConsoleApplication2.Program+Person")
Type t = typeof(List<>).MakeGenericType(passInType);

举一个完整的例子:

using System;
using System.Collections.Generic;
using System.Reflection;
namespace ConsoleApplication2 {
 class Program {
   class Person {}
   static void Main(){
       Assembly myAssembly = typeof(Program).Assembly;
       Type passInType = myAssembly.GetType(
           "ConsoleApplication2.Program+Person");
       Type t = typeof(List<>).MakeGenericType(passInType);
   }
 }
}






如注释中所建议-解释, List<> open 泛型类型-即 List< T> ,没有任何特定的 T (对于多个通用类型,您只需使用逗号-即 Dictionary&lt ;,> )。当指定了 T (通过代码或通过 MakeGenericType )时,我们将得到 closed 泛型类型-例如, List< int>


As suggested in the comments - to explain, List<> is the open generic type - i.e. "List<T> without any specific T" (for multiple generic types, you just use commas - i.e. Dictionary<,>). When a T is specified (either through code, or via MakeGenericType) we get the closed generic type - for example, List<int>.

使用 MakeGenericType ,仍然会强制执行任何泛型类型约束,而只是在运行时而不是在编译时。

When using MakeGenericType, any generic type constraints are still enforced, but simply at runtime rather than at compile time.