【问题标题】:Dynamically create a type for JsonSerializer.DeserializeAsync?为 JsonSerializer.DeserializeAsync 动态创建一个类型?
【发布时间】:2021-11-27 17:52:27
【问题描述】:

我有方法/任务,我想返回一个实现某个接口的类型。 我在选择有很多条件的类型,我有强烈的感觉,它可以做得更简单。问题是,我不知道如何动态选择类型。

没关系:

IInterface Obj;
//Type1 and Type2 implements IInterface
if(true)
{
    Obj = await JsonSerializer.DeserializeAsync<Type1>(memoryStream, JsonOpt);
    return Obj;
}
else
{
    Obj = await JsonSerializer.DeserializeAsync<Type2>(memoryStream, JsonOpt);
    return Obj;
}

这不是:

IInterface Obj;
Type type;
//Type1 and Type2 implements IInterface
if(true)
{
    type = typeof(Type1);
}
else
{
    type = typeof(Type2);
}
Obj = await JsonSerializer.DeserializeAsync<type>(memoryStream, JsonOpt);
return Obj

我知道我可以使用泛型,但归根结底,问题还是一样的。这是一些通用任务。

    public class Test
    {
        public async Task<T> Ooo<T>() where T : new()
        {
            T t = new T();
            //something awaitable here
            return t;
        }
    }

这里我要决定类型:

        Test test = new();
        Type t;
        if (true)
        {
            t = typeof(TimeZoneInfo);
        }
        else
        {
            t = typeof(TimeZone);
        }
        object obj = await test.Ooo<typeof(t)>();

【问题讨论】:

  • 我的答案中的示例代码可能有帮助吗?我不确定你的内存流来自哪里,或者你是否是它的来源 - stackoverflow.com/a/69480735/4800344
  • 我必须深入检查一下,但是是的,这可能会有所帮助。

标签: c# types


【解决方案1】:

根据the documentation,有一个非泛型重载接受您想要反序列化的类型。您只需要将返回的object 强制转换为相应的接口即可。

Type type = ...;
object result = await JsonSerializer.DeserializeAsync(memoryStream, type, JsonOpt);
return (IInterface)result;

【讨论】:

  • 问题是他们不马上知道类型
  • 你确定吗?当我阅读问题时,问题是他们根据某些条件选择了 Type 实例,但由于在编译时不知道类型,因此无法调用泛型方法。
  • 我以为他们正在尝试检查它是哪个具体类型,反序列化为具体类型,然后将具体类返回为IInterface - 这样他们就可以将其转换到方法之外?
  • 如果他们能得到正确的Type,这正是我的回答。 :)
  • if(true) 让我对他们真正想要的东西感到失望 - 你可能是对的,忽略我?
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 2011-12-21
  • 1970-01-01
  • 2017-02-23
  • 2011-09-29
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多