【问题标题】:Build c# Generic Type definition at runtime在运行时构建 c# Generic Type 定义
【发布时间】:2009-09-03 06:45:34
【问题描述】:

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

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

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

有什么东西可以让我做这样的事情(假代码):

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

或者我应该坚持我的 hack,passInType.GetType() 转换为字符串,构建泛型类型字符串.. 感觉很脏

【问题讨论】:

  • 光看你的代码示例我觉得很脏。

标签: c# generics types


【解决方案1】:

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);
   }
 }
}

正如 cmets 中的建议 - 解释一下,List&lt;&gt;open 泛型类型 - 即“List&lt;T&gt; 没有任何特定的T”(对于多个泛型类型,您只需使用逗号- 即Dictionary&lt;,&gt;)。当指定T 时(通过代码或通过MakeGenericType),我们将获得已关闭 泛型类型——例如List&lt;int&gt;

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

【讨论】:

  • 为了完整起见,添加对开放/封闭泛型类型的解释可能是个好主意。
  • MakeGenericType 正是我想要的。谢谢! :) 答案已接受
猜你喜欢
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 2013-05-31
相关资源
最近更新 更多