首页 > 解决方案 > 从 if 语句 C# 执行 else 语句

问题描述

下面是我正在使用的 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-statementconditional-statements

解决方案


也许是这样的?

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

推荐阅读