C#如果是else的优先级if if

Kai*_*Kid 0 c# if-statement

我的项目中有这段特定的代码:

if (type == 1)
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
    else if (type == 2)
        if (line.StartsWith(user.PadRight(FieldLengths2[0])))
            keep = true;
Run Code Online (Sandbox Code Playgroud)

最初,缩进是不同的.else-if应该链接到"if(type == 1)",正如内容所暗示的那样.但Visual Studio似乎已经改变了我的缩进,建议将它链接到下一个if(if(line.startswith ...))

这可能相当于

if (type == 1)
{
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
}
else if (type == 2)
{
    if (line.StartsWith(user.PadRight(FieldLengths2[0])))
        keep = true;
}
Run Code Online (Sandbox Code Playgroud)

或者对此:

if (type == 1)
{
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
    else if (type == 2)
    {
        if (line.StartsWith(user.PadRight(FieldLengths2[0])))
            keep = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道else-if如何表现没有括号,以及究竟是什么决定它会链接到哪个?

SLa*_*aks 6

else关键字始终链接到最近的关键字if.

您应该使用大括号来避免这种混淆.

  • @RandRandom"总是"和"最接近"有什么不清楚 (2认同)

Adr*_*ian 5

C#5.0语言规范在§8.7.1规定

一个else部分与最近的前一个的相关联的词汇if 是由语法允许的。