【发布时间】:2022-12-05 22:08:43
【问题描述】:
我有通用服务 IService<T> 和一些实现 ServiceA: IService<A>、ServiceB: IService<B> 提供不同类型的数据 A 和 B。
取决于我需要调用适当服务的类型,从服务中获取数据,检查是否为 null 并映射到类型 IWidget。另外,我有映射每种类型的扩展方法,例如
public static class Mapper
{
public static IWidget Map(this A data)
{
return new WidgetA{......};
}
public static IWidget Map(this B data)....
}
由于在 GetData 之后我得到未知类型,我无法调用适当的映射。我该如何重构这个结构
IWidget widget;
switch (currentItem.Type)
{
case "A":
{
var data = ServiceA.GetData(ProductAlias);
if (data == null)
{
return EmptyContent;
}
widget = data.Map();
break;
};
case "B":
{
var data = ServiceB.GetData(ProductAlias);
if (data == null)
{
return EmptyContent;
}
widget = data.Map();
break;
};
}
我想得到这样的东西
object data = currentItem.Type switch
{
"A" => ServiceA.GetData(),
"B" => ServiceB.GetData(),
_ => null
};
if (data == null)
{
return EmptyContent;
}
var widget = data.Map(); - Mapping can't be called from Object type
【问题讨论】:
标签: c# refactoring