c# - If - else 没有 else 的语句

标签 c# if-statement

有人能解释一下为什么 if - else 语句会这样工作而不抛出错误或异常吗?如果这在 C# 中是故意的,有人可以解释两者之间是否存在差异吗?

if (comboBox1.SelectedIndex == -1) { }
    {
            //code
    }

而不是使用
  if (comboBox1.SelectedIndex == -1) { }
  else {
            //code
       }

因为我注意到在我重新排列代码以使其更具可读性之后,我不小心在我的代码中做了一个类似上述的 if - else 语句。

最佳答案

第二 block 在

if (comboBox1.SelectedIndex == -1) 
{ 
    var a = 10;
}
{
    var b = 10;
}

...不是 else block ,而只是一个代码块。这里是变量 b的范围仅在 block 内。它与
if (comboBox1.SelectedIndex == -1) 
{ 
    var a = 10;
}
var b = 10;

...除了变量 b 的范围已经改变。

关于c# - If - else 没有 else 的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230134/

相关文章:

c# - 使用 Jenkins 的 Roslyn 分析器

python - 当列表值为字符串时,如何将 else 与列表理解一起使用?

JAVA试图寻找年度最佳职位。不工作

python - 如何使 python "goto"成为前一行以获得更多输入?

if-statement - 如何在9、109和209等处执行其他操作,在99、199和299等处进行其他操作,以及对以9结尾的所有其他操作执行一系列其他操作?

c# - 无法将 `System.Windows.Forms` 引用添加到我的 WCF 服务库

c# - List.Cast<> 错误 "is a method which is not valid in the given context"

c# - “字段”不是 'System.Data.DataRow' 的成员

c# - 带有面板的自己的组件

function - 如何在满足 if 条件时重新启动函数