c# - If 语句内 If 语句条件
问题描述
我有这个代码:
int a, b;
if (a > 0)
{
a--;
DoSomething()
}
else if (b > 0)
{
b--;
DoSomething();
}
我听说最好不要DoSomething();
两次写同一行(),所以有没有办法做到这一点:
int a, b;
if (a > 0 /* if true a--; */ || b > 0 /* if true b--; */)
{
DoSomething();
}
换句话说,有没有更好的方法来做到这一点(不写DoSomething();
两次):
int a, b;
if (a > 0)
{
a--;
DoSomething()
}
else if (b > 0)
{
b--;
DoSomething();
}
解决方案
如果这些是方法中唯一或最后的语句,您可以在附加的 else 语句中返回:
if (a > 0)
{
a--;
}
else if (b > 0)
{
b--;
}
else
{
return;
}
DoSomething();
如果这些是循环中的最后一个语句,您可以使用continue
而不是return
. 在开关盒中,您可以使用break
.
如果DoSomething
涉及更复杂的事情,那么使用标志是合适的。否则调用DoSomething
两次就好了。
bool isDecremented = false;
if (a > 0)
{
a--;
isDecremented = true;
}
else if (b > 0)
{
b--;
isDecremented = true;
}
if (isDecremented)
{
// Do something more complex.
}
推荐阅读
- computation-theory - 给定字母 {a,b,c,1,2,3},用有限集表示法描述 C 语言中接受的变量名称集和整数集
- python - 错误:将 pytest 与 VSCode (macOS) 一起使用时找不到文件
- sql - 使用 $$ 时 creat 的 Postgres 语法错误
- swift - 如何通过选择器设置 textField becomeFirstResponder
- ruby-on-rails - Rails 6 路线 - 简单嵌套路线的正确方法
- spring-boot - 由于 JBoss 模块中的 Log4j 版本不同,未生成日志
- ansible - 使用带有 netbox.netbox.nb_lookup 的 api_filter 中的变量时出现问题
- r - 错误:“冲突”的包或命名空间加载失败:
- r - 从 R 中每个 ID 号/行的 .sav 文件创建一个 .txt 文件
- javascript - 我想根据值更改 JavaScript 进度条颜色