【发布时间】: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
-
我必须深入检查一下,但是是的,这可能会有所帮助。