繁体   English   中英

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

[英]Build c# Generic Type definition at runtime

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

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

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

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

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

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

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 ,仍然会强制执行任何泛型类型约束,但只是在运行时而不是在编译时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM