繁体   English   中英

C# 在嵌套 Ifs 中处理 Else 条件

[英]C# Handling Else Condition Within Nested Ifs

提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文

我需要从if执行一个else语句,然后在其中执行另一个if语句。

if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) //Scenario 1
{
    if (BoxA == BoxB && BoxC == BoxD) //Scenario 2
    {
        //Do something
    }
}
else
{
    // Do something else if 
    // 1) Scenario 1 hits but not scenario 2
    // 2) Scenario 1 does not hit
}

我可以知道 go 到else语句,无论scenario 1还是scenario 2是否命中?

编辑:对场景混乱表示歉意。 已在 else 语句中按上述方式编辑


最后,我采用了以下解决方案

if ((!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) && (BoxA == BoxB && BoxC == BoxD))
{
    //do something
}

原因是因为在if期间,如果第一次 null 检查失败,它将进行第二次比较检查。 我第一次 null 检查的目的是防止第二次比较检查期间出现 null 异常。

将条件存储在 boolean 变量中。 然后你可以重用它们。

bool nullCondition = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool equalityCondition = BoxA == BoxB && BoxC == BoxD;

if (nullCondition && equalityCondition) 
{
  // Both conditions are true
}
else 
{
  // Any of equalitycondition or nullcondition is false
}

您可以将场景存储在两个 boolean 变量中,这样可以更轻松地进行检查:

bool scenario1 = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool scenario2 = BoxA == BoxB && BoxC == BoxD
if (scenario1)
{
    if (scenario2)
    {
        //do something
    }
}
if((scenario1 && !scenario2) || !scenario1)
{
    //do something else if either Scenario 1 or 2 hits.
}

根据您的具体操作,您还可以为变量指定更具表现力的名称。

我不确定我是否正确理解你的问题; 您的示例似乎想要的逻辑非常简单:

if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) 
{
    if (BoxA == BoxB && BoxC == BoxD)
    {
        //Scenario 1 & 2
    }
    else
    {
        //Scenario 1 hits but not scenario 2
    }
}
else
{
     //Scenario 1 does not hit
}
问题未解决?试试搜索: C# 在嵌套 Ifs 中处理 Else 条件
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM