【问题标题】:Go and execute else statement from if statement C#从 if 语句 C# 执行 else 语句
【发布时间】:2021-06-17 16:12:33
【问题描述】:

以下是我正在使用的 if-else 条件语句。我正在考虑删除 //Statements 2

中的代码重复
if (true)
{
    List<string> usersList=getUsersList();
    if(usersList.Length > 0){   
    //Statements 1
    ..............
    }
    else{
    //Statements 2
    .............
    }
}
else
{
    //Statements 2
    .............
}

在上面的代码中需要重复语句2。有没有办法将执行发送到主 else 循环。

【问题讨论】:

    标签: c# if-statement conditional-statements


    【解决方案1】:

    您可以使用conditional logical operator && 来完成此操作,但请注意,如果您的决策树变得更加复杂,它会很快变得混乱。

    if (condition1 && condition2) //both need to be "true" to execute statements 1
    {
       //Statements 1
    }
    
    else
    {
       //Statements 2
    }
    

    【讨论】:

    • 谢谢@Stefan。将条件 2 作为外部函数以提供异常值。但无法执行此始终应基于条件1执行。有没有办法使用 GO TO。
    • 是的,你可以这样做。我可以更新示例,但我需要您使用的名称。在您的问题中,您仅使用 true 作为条件。
    【解决方案2】:

    也许是这样的?

    bool runSecondBlock = !firstCondition;
    if (firstCondition)
    {
      List<string> usersList=getUsersList();
      if(usersList.Length > 0){   
        //Statements 1
        ..............
      }
      else {
        runSecondBlock = true;
      }
    }
    if (runSecondBlock)
    {
        //Statements 2
        .............
    }
    

    【讨论】:

    • 这可以用一些评论来做,但这是我的首选,即使我们可以使用匿名委托或动作,使用故意标志会使复杂的决策逻辑使代码非常容易测试和维护。甚至可以为文档留出大量空间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2020-09-06
    • 2017-10-28
    相关资源
    最近更新 更多