c# - If 语句或拆分中的多个条件

标签 c# c++ compiler-construction

当我在多个条件下使用 if 语句时,它们在编译器中是如何管理的?

A) 如果第一个语句未满足,它会忽略第二个语句吗?反之亦然?

If(time > 3.0 && hitEnabled)

B) 通常推荐后期定义,所以我应该更喜欢在 if 语句中使用一个条件吗?

if(time > 3.0)
    if(hitEnabled)

谢谢!

最佳答案

if(time > 3.0 && hitEnabled)

在上面的语句中,当 time > 3.0 为 false 时,hitEnabled 将不会被计算。

这称为短路。

即使 time > 3.0 为 false,以下语句也会计算 hitEnabled,但当两个操作数都为 true 时返回 true。

if(time > 3.0 & hitEnabled)//note bitwise &

if(time > 3.0)
    if(hitEnabled)

当您需要多次检查第一个条件等时,嵌套 if 语句很有用。

if(time > 3.0 && hitEnabled)
{
//DoSomething1
}
if(time > 3.0 && flag)
{
//DoSomething2
}

这可以用嵌套的 if 语句重写如下

if(time > 3.0)
{
    if(hitEnabled)
    {
    //DoSomething1
    }
    if(flag)
    {
    //DoSomething2
    }
}

在这种情况下,我更喜欢嵌套的 if 语句以避免不必要的检查

关于c# - If 语句或拆分中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19357134/

相关文章:

syntax - 二郎 : variable 'Result' unsafe in 'try'

c# - 只读静态记录器字段的标准命名约定是什么?

c# - 仅迭代集合中的一部分元素

c++ - vector 类应该有什么构造函数/赋值运算符?

c++ - 一个类的双重部分模板特化

C 编程 - 编写可自行编译的文本文件

c# - 为什么我必须执行转换为值元组内的对象?

c# - MonoMac/Xamarin.Mac 上的 PCLStorage - NotImplementedException?

c++ - 使用抽象类的子类专门化模板

c++ - 编译器如何管理返回内联函数?