在运行时构建c#Generic Type定义
目前我不得不做这样的事情来在运行时构建一个Type定义传递给我的IOC来解决。 简化:
Type t = Type.GetType( "System.Collections.Generic.List`1[[ConsoleApplication2.Program+Person");
我只知道运行时的generics类型参数。
有什么东西可以让我做这样的事情(假代码):
Type t = Type.GetTypeWithGenericTypeArguments( typeof(List) , passInType.GetType());
或者我只是坚持我的hack, passInType.GetType()
转换为字符串,构建generics类型字符串..感觉脏
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<>
是开放的generics类型 – 即“ List
没有任何特定的T
”(对于多种generics类型,你只需使用逗号 – 即Dictionary<,>
)。 当指定T
(通过代码或通过MakeGenericType
),我们得到封闭的generics类型 – 例如, List
。
使用MakeGenericType
,仍会强制执行任何generics类型约束,但只是在运行时而不是在编译时。