c# - 从我的方法中替换 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...
}
解决方案
您可以声明一个带有字符串类型键的字典,用于存储操作。
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);
}
}
推荐阅读
- jquery - 未达到 jQuery on() 方法
- javascript - 微服务快递网关中的 Socket.io 集成
- python - for 循环内的字典未按预期工作 TypeError:replace() 至少需要 2 个参数(给定 1 个)
- r - 如何将 geom_point、geom_bar 和 geom_errobar 与 position_dodge 对齐
- react-native - react-native flatlist 在项目删除/向上滑动时制作动画
- javascript - 用于 cookie 匹配的正则表达式
- git - 为什么使用 git 从 powershell 复制的二进制文件与原始文件不同?
- google-apps-script - 谷歌脚本根据数据变化改变行颜色,工作表排序
- go - Go test 可以访问生产函数但不能访问测试函数
- javascript - 如何将数字或字符转换为 MathML 格式?