Using else with multiple if statements C#

2019-05-29 19:49发布

Is there a way to quickly check the following logic? I'm using C#.

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

This differs from using if-else in that a, b, and c can all be true at once. So I can't stack them that way. I want to check else for a, b, and c are all false without writingif(!a && !b && !c). This is because the code can get quite messy when the if conditions become more complex. It requires rewriting a lot of code. Is this possible?

3条回答
一夜七次
2楼-- · 2019-05-29 19:53

Rather than encapsulate some complex condition in a method that you will only ever call once or twice, I would just keep in a variable. This is also more readable than using some marker boolean as other answers suggest.

A contrived example,

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)
{
}

Now we have abstracted what might otherwise be complex conditions into readable English!

查看更多
太酷不给撩
3楼-- · 2019-05-29 19:59

Well it's not pretty "clean", but I'd do

bool noneAreTrue = true;
if(a)
{
    noneAreTrue = false;
}
if(b)
{
    noneAreTrue = false;
}
if(c)
{
    noneAreTrue = false;
}
if(noneAreTrue)
{
    //execute if all above conditions are false
}

Also, if your conditions are really pretty big, I recommend the rule G28 (Encapsulate Conditionals) from the book Clean Code from Robert C. Martin

It is pretty verbose, but can be easier to read in some instances :

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();
}
查看更多
Emotional °昔
4楼-- · 2019-05-29 20:14

How about combine the concepts of Strategies and Specifications

var strategies = _availableStrategies.All(x => x.IsSatisfiedBy(value));
foreach (var strategy in strategies)
{
    strategy.Execute(context);
}
if (!strategies.Any()) {
    // run a different strategy
}
查看更多
登录 后发表回答