C#与else之间的区别if和if

时间:2017-02-06 21:04:31

标签: c#-4.0

在C#中if和else之间有什么区别?例如,如果我写

if (x==5){
    do something
}

并且

else if (x==5){
    do something
}

他们是完全相同的......所以?有什么区别?

3 个答案:

答案 0 :(得分:4)

**IF** you are confused
 read the c# spec
**ELSE IF** you are kind of confused
 read some books
**ELSE**
 everything should be OK.

礼貌:https://stackoverflow.com/a/1445365/5352399

笑话是分开的,通常是if语句遵循这种结构:

if (condition)
{
    // executed only if "condition" is true
}
else if (other condition)
{
    // executed only if "condition" was false and "other condition" is true
}
else
{
    // executed only if both "condition" and "other condition" were false
}

if部分是唯一绝对强制的块。 else if允许你说“好吧,如果先前的条件不成立,那么如果这个条件是真的......”。否则说“如果以上条件都不属实......”

您可以拥有多个else if块,但只有一个if块,只有一个(或零)else块。

答案参考:https://stackoverflow.com/a/1439915/5352399

请阅读C# control statements,了解全面的信息。

答案 1 :(得分:1)

他们不一样。

if (true)
 DoSomething();

if (true)
 DoSomething();

对战

if (true)
  DoSomething();
else if (true)
  DoSomething();

第一个例子做了两次事;第二个只做一次。

当你不想要多个案件被击中时使用别人。

答案 2 :(得分:0)

这有点棘手,如果您使用诸如resharper之类的插件,并尝试在else if句子之前编写if句子,则resharper会告诉您'else if'句子中的'else'是多余的,并将重构您的仅在句子中编码。

性能问题?还是我们现在真的不知道c#的工作方式?

相关问题