简体   繁体   English

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

[英]Build c# Generic Type definition at runtime

At present I'm having to do something like this to build a Type definition at runtime to pass to my IOC to resolve.目前我不得不做这样的事情来在运行时构建一个类型定义来传递给我的 IOC 来解决。 Simplified:简化:

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

I know the generic type argument at runtime only.我只知道运行时的泛型类型参数。

Is there something that will allow me to do something like this (fake code):有没有什么可以让我做这样的事情(假代码):

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

Or shall I just stick to my hack, passInType.GetType() convert to string, build generic type string.. feel dirty或者我应该坚持我的技巧, passInType.GetType()转换为字符串,构建通用类型字符串.. 感觉很脏

MakeGenericType - ie MakeGenericType - 即

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

For a complete example:一个完整的例子:

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

As suggested in the comments - to explain, List<> is the open generic type - ie " List<T> without any specific T " (for multiple generic types, you just use commas - ie Dictionary<,> ).正如评论中所建议的 - 解释一下, List<>开放的泛型类型 - 即“ List<T>没有任何特定的T ”(对于多个泛型类型,您只需使用逗号 - 即Dictionary<,> )。 When a T is specified (either through code, or via MakeGenericType ) we get the closed generic type - for example, List<int> .当指定T (通过代码或通过MakeGenericType )我们得到封闭的泛型类型 - 例如, List<int>

When using MakeGenericType , any generic type constraints are still enforced, but simply at runtime rather than at compile time.使用MakeGenericType ,仍然会强制执行任何泛型类型约束,但只是在运行时而不是在编译时。

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

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