首页 > 解决方案 > 从我的方法中替换 IF 和 Else If 语句

问题描述

如果它是以下方法,我需要一些帮助。场景是我在后端机器上有一个传入的订单。在我可以处理它之前,我需要根据客户需求对订单做一些事情。可能是清理一些电话号码或向订单添加数据。无论如何,需要为每个客户完成的工作是相当独特的,所以我现在不想讨论。

现在我更想知道我是否可以用不同的方式处理下面的问题,因为当客户堆积起来时,else if、else if、else if 也是如此,我开始不喜欢它。我应该做出 switch 声明还是有更好的眼睛友好的方式?

private void SenderSpecificLogic(Order order)
    {
        if (order.Customer.IsEqualIgnoreCase("abc"))
            AbcCustomerOrderManipulationLogic(order);

        else if (order.Customer.IsEqualIgnoreCase("bcd"))
            BcdCustomerCustomerLogic(order);
      
        else if (order.Customer.IsEqualIgnoreCase("cde"))
            CdeCustomerOrderManipulationLogic(order);            
       
        else if (order.Customer.IsEqualIgnoreCase("def"))
            DefCustomerOrderManipulationLogic(order);

        // and the list goes on an on...

    }

标签: c#if-statement

解决方案


您可以声明一个带有字符串类型键的字典,用于存储操作。

private void SenderSpecificLogic(Order order)
{
    // Actions could be defined outside SenderSpecificLogic.
    var Actions = new Dictionary<string, Action<Order>>
    {
        { "abc", AbcCustomerOrderManipulationLogic },
        { "def", DefCustomerOrderManipulationLogic },
        { "ghi", GhiCustomerOrderManipulationLogic },
        { "jkl", JklCustomerOrderManipulationLogic },
        { "mno", MnoCustomerOrderManipulationLogic },
        // Etc...
    }

    var Customer = order.Customer.ToLower();

    if(Actions.ContainsKey(Customer))
    {
        Actions[Customer](Order);
    }
}

推荐阅读