rom*_*n m 13 c# language-features short-circuiting
我有几种方法可以根据它们的成功返回bool,在IF()中调用这些方法有什么问题吗?
//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
Run Code Online (Sandbox Code Playgroud)
如果Method1()返回FALSE,则不需要触发Method2().
让我知道上面的代码有任何问题.
谢谢.
编辑:因为代码没有任何问题,我会接受最丰富的答案...添加评论来解决"newbie &&&"问题
Joh*_*sch 21
我会投入你可以使用& operator(而不是&&)来保证两个方法都被调用,即使左边是false,如果由于某种原因将来你想避免短路.
对于| operator即使左手条件评估的true情况,也将评估右手条件.
chi*_*s42 19
不,if条件中的方法调用没有任何问题.实际上,这可以是让代码更具可读性的好方法!
例如,写起来要干净得多:
private bool AllActive()
{
return x.IsActive && y.IsActive && z.IsActive;
}
if(AllActive())
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
比:
if(x.IsActive && y.IsActive && z.IsActive)
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10052 次 |
| 最近记录: |