gpt4 book ai didi

c# - 从字符串实例化泛型

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

我要Instantiate a generic type from string并完成了以下工作:

    private static void APERAK(string content, PartyElement pe, bool reload)
{
Type t = typeof(Serializer<>).MakeGenericType(Type.GetType(GetMessageTypeVersion(content)));
Serializer<t> serializer = new Serializer<t>();
}

private static string GetMessageTypeVersion(string content)
{
//TODO
return "APERAK";
}

但是在

Serializer<t> serializer = new Serializer<t>();

它说“找不到类型或 namespace 名称‘t’(是否缺少 using 指令或程序集引用?)”在编译之前。但我想根据找到的字符串实例化序列化程序。我该怎么做?

最佳答案

您已经拥有具有以下内容的通用类型:

typeof(Serializer<>).MakeGenericType(...);

您需要做的就是实例化它:

object o = ACtivator.CreateInstance(t);

编译器当然不知道是什么类型 t是的,因此你将无法在没有反射的情况下使用它的方法/属性,所以泛型在这里并不能真正帮助你。你能做的最好的事情就是强制转换为 Serializer<> 的非泛型基类。 (假设存在)。

关于c# - 从字符串实例化泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17277922/

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