本文介绍了在运行时构建 c# 通用类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 目前我不得不做这样的事情来在运行时构建一个类型定义来传递给我的 IOC 来解决.简化:At present I'm having to do something like this to build a Type definition at runtime to pass to my IOC to resolve. 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());或者我应该坚持我的 hack,passInType.GetType() 转换为字符串,构建通用类型字符串.. 感觉很脏Or shall I just stick to my hack, passInType.GetType() convert to string, build generic type string.. feel dirty推荐答案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 是 open 泛型类型 - 即List 没有任何特定的 T"(对于多个泛型类型,您只需使用逗号 - 即 Dictionary<,>).当指定 T 时(通过代码或通过 MakeGenericType),我们得到 closed 泛型类型 - 例如,List.As suggested in the comments - to explain, List<> is the open generic type - i.e. "List<T> without any specific T" (for multiple generic types, you just use commas - i.e. Dictionary<,>). When a T is specified (either through code, or via MakeGenericType) we get the closed generic type - for example, List<int>.当使用 MakeGenericType 时,任何泛型类型约束仍然被强制执行,但只是在运行时而不是在编译时.When using MakeGenericType, any generic type constraints are still enforced, but simply at runtime rather than at compile time. 这篇关于在运行时构建 c# 通用类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-06 22:01