目前我不得不做这样的事情来在运行时构建一个Type定义传递给我的IOC来解决.简化:
Type t = Type.GetType(
"System.Collections.Generic.List`1[[ConsoleApplication2.Program+Person");
Run Code Online (Sandbox Code Playgroud)
我只知道运行时的泛型类型参数.
有什么东西可以让我做这样的事情(假代码):
Type t = Type.GetTypeWithGenericTypeArguments(
typeof(List)
, passInType.GetType());
Run Code Online (Sandbox Code Playgroud)
或者我只是坚持我的黑客,passInType.GetType()转换为字符串,构建泛型字符串..感觉很脏
Mar*_*ell 34
MakeGenericType - 即
Type passInType = ... /// perhaps myAssembly.GetType(
"ConsoleApplication2.Program+Person")
Type t = typeof(List<>).MakeGenericType(passInType);
Run Code Online (Sandbox Code Playgroud)
有关完整示例:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论中所建议的 - 解释,List<>是开放的泛型类型 - 即" List<T>没有任何特定T"(对于多种泛型类型,你只需使用逗号 - 即Dictionary<,>).当T指定a时(通过代码或通过MakeGenericType),我们得到封闭的泛型类型 - 例如,List<int>.
使用时MakeGenericType,仍会强制执行任何泛型类型约束,但只是在运行时而不是在编译时.