在C#中是否存在if语句? [英] Do else if statements exist in C#?
问题描述
我在C#中遇到过以下代码。
I have come across the following code in C#.
if(condition0) statement0;
else if(condition1) statement1;
else if(condition2) statement2;
else if(condition3) statement3;
...
else if(conditionN) statementN;
else lastStatement;
我的一些同事告诉我,这是否则
声明。但是,我确信它实际上是一个多层嵌套的 if-else
语句。我知道如果没有分隔符 {}
,如果或 else <,则允许在
中使用一条语句/ code>。所以在这种情况下我认为它等同于以下代码。
Some of my colleagues tell me that this is an else if
statement. However, I am convinced that it is actually a multi-layered nested if-else
statement. I know that without delimiters {}
, one statement is allowed in an if
or else
. So in this case I think it would be equivalent to the following code.
if(condition0)
statement0;
else
if(condition1)
statement1;
else
if(condition2)
statement2;
else
if(condition3)
statement3;
else
...
请注意,我改变的只是空格。
这个缩进是有效的,因为当没有分隔符时,每个 else
都会返回到最近的 if
语句。
Note that all I changed was the whitespace.
This indentation works because each else
goes back to the most recent if
statement when there are no delimiters.
任何人都可以澄清第一个例子中的 else if
格式是否被编译器区别对待嵌套<第二个例子中的code> if-else 格式?
Can anyone clarify if the else if
format in the first example is treated differently by the compiler than the nested if-else
format in the second example?
推荐答案
你是对的;在C#中没有else if语句这样的东西。这只是替代子句的声明本身就是if语句的其他部分。
You are correct; there is no such thing as an "else if" statement in C#. It's just an else where the statement of the alternative clause is itself an if statement.
当然, IDE 将else if视为特别的,以便你得到你期望的漂亮格式。
Of course, the IDE treats "else if" as special so that you get the nice formatting you'd expect.
注意是 #elif
以预处理器语法构造。
Note that there is an #elif
construct in the "preprocessor" syntax.
还要注意C,C ++和ECMAScript - 我相信还有更多类C语言 - 也有没有正式else if声明的财产。相反,在每个行为中,else的定义都落在单个陈述之前。
Note also that C, C++ and ECMAScript - and I am sure many more C-like languages - also have the property that there is no formal "else if" statement. Rather, in each the behaviour falls out of the definition of "else" as coming before a single statement.
这篇关于在C#中是否存在if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!