gpt4 book ai didi

c# - 从不同 dll 中的字符串值表示中获取泛型类型

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:01 25 4
gpt4 key购买 nike

我有 3 种类型,全部来自不同的 dll,你找不到如何在字符串中存储通用类型以及如何创建实例:

Type type1 = GetType1();
Type type2 = GetType2();
string strClassGenericType = "Namespace.ClassName<,>, DllName";

Type template = // How to get the generic template type?

Type genericType = template.MakeGenericType(new[] { type1, type2 });
object instance = Activator.CreateInstance(genericType);

我不确定 this符合我的要求。

最佳答案

在特定情况下,如果您希望对象的类型不知道其类型参数,则可以使用带有类型参数数量的反引号。下面是一个使用 Tuple 的例子:

Console.WriteLine(typeof (Tuple<,>).FullName); //For information only, outputs "System.Tuple`2"
var typeName = "System.Tuple`2";
var type = Type.GetType(typeName);
var generic = type.MakeGenericType(typeof (string), typeof (int));
Console.WriteLine(generic.FullName); //Outputs the type with the type parameters.

关于c# - 从不同 dll 中的字符串值表示中获取泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29356444/

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