很难制定标题。 但是,我会尽快解释我目前的选择,希望有人能告诉我一个更好的方法来完成这项工作。c# - 基于Bool而无if语句的方法调用
第一个“快”的解决方案,我们不得不为:
public class Test
{
public bool UseSomething = false;
public bool UseSomethingElse = false;
public bool UseAnother = false;
public void MyMethod(){
if(UseSomething){
if(UseSomethingElse){
if(UseAnother){
// UseSomething, UseSomethingElse, UseAnother
}
else{
// UseSomething, UseSomethingElse
}
}
else{
// UseSomething
}
}
else if(UseSomethingElse){
if(UseAnother){
// UseSomethingElse, UseAnother
}
else{
// UseSomethingElse
}
}
// etc...
}
}
现在,这是在我看来,一个丑陋的解决方案,并成为真正的快速混乱,特别是如果你想添加的选项。更不用说,除了我自己以外,任何人都会一见钟情,不知道去哪里/改变什么。
所以我很快想出了另一种解决方案如下:
public class Test
{
public bool UseSomething = false;
public bool UseSomethingElse = false;
public bool UseAnother = false;
short options = 0;
public void Init() // call this @ start of your program
{
if (UseSomething)
options += 1;
if (UseSomethingElse)
options += 2;
if (UseAnother)
options += 4;
}
public void MyMethod(){
Something something = MatchOption(foo);
}
public void MatchOption(Foo foo)
{
switch (options) // based on the Options value (which is unique for every bool-triggered) perform a specific method.
{
case 0: //000
return NoOptions(foo);
case 1: //100
return OptionSomething(foo);
case 2: //010
return OptionSomethingElse(foo);
case 4: //001
return ... etc;
case 3: //110
break;
case 5: //101
break;
case 6: //011
break;
case 7: // 111
break;
case -1:
return;
}
}
}
现在,这使得它更易于管理和人基本上就不会担心这if/else语句把东西此外,这些方法是干净的,只做他们应该做的事情。
但我仍然不能放过它,必须有其他方式来做到这一点。
这不是一个代码不起作用的问题。我更想要一个“最好”或“最干净”的方式来做到这一点。^_^ 我是第三年软件工程师学生,仍然在寻找清理或优化代码的方法。
如果您有任何意见或建议,请让我知道!
注意:这主要是伪代码,我没有运行或测试过这个。这不是关于工作,这是我想弄明白的一个概念。
此问题似乎是脱离主题,因为它是关于代码审查,因此它属于http://codereview.stackexchange.com/ – 2014-10-28 10:04:33
相关:[如果语句为多个方案](http://stackoverflow.com/q /335858分之26347287)。 – dasblinkenlight 2014-10-28 10:08:45
所有DoSomething函数都具有相同的签名吗? – user3613916 2014-10-28 10:11:00