Using else with multiple if statements C#

点点圈 提交于 2019-12-08 01:59:27

问题


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?


回答1:


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



回答2:


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
}



回答3:


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!



来源:https://stackoverflow.com/questions/16952769/using-else-with-multiple-if-statements-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!