<分区>
很难制定一个标题。 不过,我会快速解释我当前的选择,希望有人能告诉我一种更简洁的方法来完成这项工作。
我们的第一个“快速”解决方案是:
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 语句。而且这些方法很干净,只做他们应该做的事情。
但我仍然不能放弃,必须有其他方法来做到这一点。
这不是代码无法运行的问题。我更想要一种“最好”或“最干净”的方式来做到这一点。 ^_^ 我是三年级的软件工程师学生,仍在寻找清理或优化我的代码的方法。
如果您有任何意见或建议,请告诉我!
注意:这主要是伪代码,我还没有运行或测试过它。这与工作无关,这是我试图弄清楚的概念。