c# - 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.
解决方案
我认为switch
语句不是布尔变量的好选择。只需比较这些代码:
if(boolVariable)
{
//...
}
else
{
//...
}
它是等价的
switch(boolVariable)
{
case true:
//...
break;
case false: // or default:
//...
break;
}
IMOif
声明更清晰、可读性和可维护性更高:)
推荐阅读
- python - 如何更改 tf.keras 以使 _Merge 类公开可用?
- android - 小球原生组件显示当前页面
- python - 如何在 requirements.txt 中添加 git 源
- aws-alb - 我们可以重命名 AWSALB cookie 吗?
- dialogflow-es - 如果没有响应,则在移动设备上重新提示用户
- java - ObjectMapper 通过 API Gateway 破坏 AWS Lambda
- gitlab - 如何添加本地 git 项目并将其推送到远程分支
- angular - Kubernetes 上的 Angular(入口路由)
- java - 我应该使用静态绑定吗?
- java - 多线程不使用同步