c# - 改进 If else 语句编码

标签 c# c#-4.0

我有一个包含“添加”和“减去”的下拉列表。当用户选择其中之一时,它将调用函数Calculate()

private int Calculate(string sAction)
{
   int iTotal = 0;
   if(sAction == "Add")
   {
       iTotal = X + Y;
   }
   else if(sAction == "Subtract")
   {
       iTotal = X-Y;
   }       
   return iTotal;
}

我不想对其进行硬编码来比较操作。看起来不符合开闭原则。如果我更改下拉列表中的文本,我也需要更改功能。我可以知道如何改进这段代码吗?

最佳答案

当你有一个代码时,请确保它具有 if else 链,应该有改进,所以这里是我的建议:

你可以使用这样的东西:

首先添加一个类来管理您的操作:

 public class ActionManager : Dictionary<string, Func<int, int, int>>
    {
        public ActionManager()
        {
            this.Add("action", (x, y) => x + y);
            this.Add("Subtract", (x, y) => x - y);
        }

    }

然后你可以像这样使用该类:

public class DoStuff
{
    private int Calculate(string sAction)
    {
        var actionManager = new ActionManager();
        var a = 1;
        var b = 2;
        //var actionResult= actionManager[this should come from your drop down].Invoke(a, b);
        var actionResult= actionManager[sAction].Invoke(a, b);


        //you can even Register New Action Like this :
        actionManager.Add("Multiply",(x,y)=>x*y);

        //then you can use it somewhere else:
        var multiplyResult =  actionManager["Multiply"].Invoke(a, b);
        return actionResult;
    }
}

因此每次您的操作发生更改时,您只需在 ActionManager 中添加新操作即可。使用这种方法就不需要 if else 语句。

顺便说一句,您甚至可以使用接口(interface)和 DI 来松散耦合 ActionManager。

关于c# - 改进 If else 语句编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46658560/

相关文章:

c# - 优化泛型方法逻辑

c# - 为什么我们需要在 C# 中锁定和对象?

c# - 为什么在finally block 中休眠时线程不被中断

c# - 最佳实践 : successfully merge two software?

c# - 使用 HttpClient 的最佳实践

asp.net - 无法创建特殊字符的图像

c# - 以不同的方式加入列表

asp.net-mvc - MVC 4中的脚手架 Controller ,错误: "Error: Unable to retrieve metadata for ' Model'.的解决方案参数 'connectionstring'不能为空

c# - 通过依赖注入(inject)将配置传递给 webjobs

c# - 比较两个函数的负载/性能