在运行时构建c#Generic Type定义

时间:2009-09-03 06:45:35

标签: c# generics types

目前我不得不做这样的事情来在运行时构建一个Type定义传递给我的IOC来解决。简化为:

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

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

是否有某些东西可以让我做这样的事情(假代码):

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

或者我只是坚持我的黑客,passInType.GetType()转换为字符串,构建泛型字符串..感觉很脏

1 个答案:

答案 0 :(得分: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<>开放泛型类型 - 即“List<T>没有任何特定的T”(对于多个通用类型,你只需使用逗号 - 即Dictionary<,>)。如果指定T(通过代码或通过MakeGenericType),我们会获得已关闭泛型类型 - 例如,List<int>

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

相关问题