如何重构这个交换机结构



我有通用服务IService<T>和一些实现ServiceA: IService<A>,ServiceB: IService<B>,提供不同类型的数据AB。取决于类型,我需要调用适当的服务,从服务获取数据,检查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

不能调用Map,因为它不属于object

也许object data = ...应该有一个不同的类型或者interface?

IMyType data = currentItem.Type switch

或者可以强制转换数据,如:

var widget = ((MyTypeWithMapFunction)data).Map();

最新更新