那么它不是很“干净”,但我会做
bool noneAreTrue = true;
if(a)
{
noneAreTrue = false;
}
if(b)
{
noneAreTrue = false;
}
if(c)
{
noneAreTrue = false;
}
if(noneAreTrue)
{
//execute if all above conditions are false
}
另外,如果你的条件真的是相当大的,我从书上清洁代码由Robert推荐规则G28(包封物条件语句) C.马丁
这是相当冗长,但在某些情况下更容易阅读:
public void YourMethod()
{
if(SomeComplexLogic())
{
}
if(SomeMoreLogic())
{
}
if(EvenMoreComplexLogic())
{
}
if(NoComplexLogicApply())
{
}
}
private bool SomeComplexLogic(){
return stuff;
}
private bool EvenMoreComplexLogic(){
return moreStuff;
}
private bool EvenMoreComplexLogic(){
return evenMoreStuff;
}
private bool NoComplexLogicApply(){
return SomeComplexLogic() && EvenMoreComplexLogic() && EvenMoreComplexLogic();
}
对于复杂的情况可以,但可能不会只有3例。 – Guillaume
引用问题“这是因为如果条件变得更复杂,代码可能会变得非常混乱,它需要重写很多代码。”其他解决方案只是丑陋的,并没有帮助可维护性。你也可以使用Func和/或Actions而不是我给的解决方案,这可能会简化实现。 – Alistair
是的,我喜欢你的解决方案,我认为它是最干净的,这就是为什么我选择了它。但要使用它,你确实需要确保有一个复杂的场景,因为在简单的情况下,所有背后的工作可能都不值得。也许你可以在你的回答中显示IStrategy的实现。 – Guillaume