【问题标题】:How to refactor this switch construction如何重构这个开关结构
【发布时间】:2022-12-05 22:08:43
【问题描述】:

我有通用服务 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

【问题讨论】:

标签: c# refactoring


【解决方案1】:

无法调用 Map,因为它不属于 object

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

IMyType data = currentItem.Type switch

或者,也许您可​​以投射数据,如:

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

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多