简体   繁体   English

C#if if是else if的优先级

[英]C# Which if is the priority for an else if

I have this specific piece of code in my project: 我的项目中有以下特定代码:

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;

Originally, the indenting was different. 最初,缩进是不同的。 The else-if is supposed to to be linked to "if (type == 1)", as the content would suggest. 如内容所示,else-if应该链接到“ if(type == 1)”。 But Visual Studio seems to have changed my indentation to suggest that it is instead linked to the next if (if (line.startswith...)) 但是Visual Studio似乎改变了我的缩进方式,建议改为将其链接到下一个if(如果(if(line.startswith ...))

This could be equivalent to 这可能相当于

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;
}

Or to this: 或对此:

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;
    }
}

I would like to know how does the else-if behave without brackets, and what exactly decides which if it would be linked to? 我想知道else-if在没有括号的情况下的行为,以及如何确定将其链接到哪个呢?

The else keyword is always linked to the closest if . else关键字始终链接到最接近的if

You should use braces to avoid this confusion. 您应该使用花括号来避免这种混乱。

The C# 5.0 Language Specification states in §8.7.1 C#5.0语言规范在§8.7.1中规定

An else part is associated with the lexically nearest preceding if that is allowed by the syntax. if语法允许,则else部分与词汇上最接近的前导相关联。

Documentation on https://msdn.microsoft.com/en-us/library/aa664812(v=vs.71).aspx says: https://msdn.microsoft.com/zh-cn/library/aa664812(v=vs.71).aspx上的文档说:

pp-conditional:   pp-if-section   pp-elif-sectionsopt   pp-else-sectionopt   pp-endif

So, else keyword is matched greedy to the closest if. 因此,else关键字贪婪地匹配到最接近的if。

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

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