我有一个包含“添加”和“减去”的下拉列表。当用户选择其中之一时,它将调用函数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/