gpt4 book ai didi

.net - 从名称实例化泛型的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-01 08:21:06 25 4
gpt4 key购买 nike

假设我只有一个泛型的类名作为“MyCustomGenericCollection(of MyCustomObjectClass)”形式的字符串并且不知道它来自哪个程序集,那么创建该对象实例的最简单方法是什么?

如果有帮助,我知道该类实现了 IMyCustomInterface 并且来自加载到当前 AppDomain 的程序集。

Markus Olsson 举了一个很好的例子 here ,但我不知道如何将它应用于泛型。

最佳答案

一旦你解析它,使用 Type.GetType(string)获取对所涉及类型的引用,然后使用 Type.MakeGenericType(Type[])构造您需要的特定泛型类型。然后,使用 Type.GetConstructor(Type[])获取对特定泛型类型的构造函数的引用,最后调用 ConstructorInfo.Invoke获取对象的实例。

Type t1 = Type.GetType("MyCustomGenericCollection");
Type t2 = Type.GetType("MyCustomObjectClass");
Type t3 = t1.MakeGenericType(new Type[] { t2 });
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);

关于.net - 从名称实例化泛型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/130208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com