使用带有多个if语句的else C#

有没有办法快速检查以下逻辑? 我正在使用C#。

if(a) { } if(b) { } if(c) { } else none of the above //...? execute if all above conditions are false { } 

这与使用if-else不同,因为a,b和c都可以同时为真。 所以我不能那样堆叠它们。 我想检查其他的a,b和c都是假的而不写if(!a && !b && !c) 。 这是因为当if条件变得更复杂时,代码会变得非常混乱。 它需要重写大量代码。 这可能吗?

嗯,它不是很“干净”,但我会这样做

 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 C. Martin的书“清洁代码”中的规则G28(Encapsulate Conditionals)。

非常冗长 ,但在某些情况下可以更容易阅读:

 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(); } 

如何结合战略和规范的概念

 var strategies = _availableStrategies.All(x => x.IsSatisfiedBy(value)); foreach (var strategy in strategies) { strategy.Execute(context); } if (!strategies.Any()) { // run a different strategy } 

而不是将一些复杂的条件封装在一个你只会调用一次或两次的方法中,我只会保留一个变量。 这比其他答案所暗示的使用某些标记布尔值更具可读性。

一个人为的例子,

 bool isBlue = sky.Color == Colors.Blue; bool containsOxygen = sky.Atoms.Contains("oxygen") && sky.Bonds.Type == Bond.Double; bool canRain = sky.Abilities.Contains("rain"); if(isBlue) { } if(containsOxygen) { } if(canRain) { } if(!isBlue && !containsOxygen && !canRain) { } 

现在我们已经把可能是复杂条件的东西抽象成可读的英语!