首页 > 解决方案 > C# switch clause on boolean variable

问题描述

I have a piece of code, that is checking if a boolean variable is true and based on the condition, I perform operations accordingly:

bool result = true;
bool isTrue = false;
CheckIsTrue(ref isTrue);

if (result)
{
   if (isTrue)
   //Perform action
}

I have a need to perform another operation, if the variable is set to false:

 if (result)
 {
    if (isTrue)
    {
      //Perform action
    } 
    else if(actionType == 6)
    {
      //Perform action, isTrue = false.
    }
 }

For readability and maintainability reason, I decided to change the above to:

 if (result)
 {
     switch (isTrue)
     {
       case true:
               //perform action on isTrue
           break;
              default:
                   switch (actionType)
                   {
                      case 6:
                         //Perform action on 6
                       break;
                          default:
                        //Perform default action        
                       break;
                   }
            break;
     } 
}

My question is: is it smart to use swicth.. case... on boolean variables? This is the best way I have considered to simplify my code, however I am not sure on how correct this truly is.

标签: c#switch-statementboolean

解决方案


我认为switch语句不是布尔变量的好选择。只需比较这些代码:

if(boolVariable)
{
  //...
}
else
{
  //...
}

它是等价的

switch(boolVariable)
{
  case true:
    //...
    break;
  case false: // or default:
    //...
    break;
}

IMOif声明更清晰、可读性和可维护性更高:)


推荐阅读