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

14

目前,我需要像这样在运行时构建类型定义,并将其传递给我的IOC进行解析。简化的代码如下:

Type t = Type.GetType(
"System.Collections.Generic.List`1[[ConsoleApplication2.Program+Person");

我知道泛型类型参数只能在运行时确定。

是否有方法可以实现类似以下的操作(伪代码):

Type t = Type.GetTypeWithGenericTypeArguments(
    typeof(List)
    , passInType.GetType());

或者我只是坚持我的hack,passInType.GetType() 转换成字符串,构建泛型类型字符串.. 感觉很不好


14
阅读你的代码示例让我感到很不爽。 - Taylor Leese
1个回答

34
`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<>是开放式泛型类型,即“没有特定 TList<T>”(对于多个泛型类型,只需使用逗号,例如 Dictionary<,>)。当指定 T 时(通过代码或通过 MakeGenericType),我们得到封闭式泛型类型,例如 List<int>
使用 MakeGenericType 时,任何泛型类型约束仍然被执行,但仅在运行时而不是在编译时执行。

为了完整起见,添加关于开放/封闭泛型类型的解释可能是一个好主意。 - Arnis Lapsa
MakeGenericType正是我正在寻找的。谢谢! :) 答案已被接受。 - rdadev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接