【问题标题】:C# difference between else if and ifC# else if 和 if 的区别
【发布时间】:2017-02-06 21:04:30
【问题描述】:

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

if (x==5){
    do something
}

还有

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

它们完全一样吗……所以?有什么区别?

【问题讨论】:

  • 您只能在初始的if 之后使用else。如果前面的if 检查失败,else if(condition) 基本上是一个新的检查。您应该阅读基本的 c# 控制运算符。
  • 你不会通过在 stackoverflow 上提问来学习编程语言。先阅读初学者书籍,了解语言的基本语法,遇到初学者书籍未涵盖的问题,再到stackoverflow。

标签: c#-4.0


【解决方案1】:
**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 表示“如果上述条件都不为真……”

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

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

请阅读C# control statements,这将为您提供全面的想法。

【讨论】:

  • 所以基本上 else if(){} 和 else{if(){}} 是一样的,对吧?每次我写 else if 就像我写 else{if(){}}
【解决方案2】:

它们不一样。

if (true)
 DoSomething();

if (true)
 DoSomething();

对比

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

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

当您不希望遇到多个案例时,请使用 else。

【讨论】:

    【解决方案3】:

    这有点棘手,如果你使用 resharper 之类的插件,并且你尝试在 else if 语句之前写一个 if 语句,resharper 会告诉你 'else if' 语句中的 'else' 是多余的,并且会重构你的代码仅用于 if 语句。

    性能问题?或者我们真的不知道现在 c# 是如何工作的?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2013-01-14
      • 2014-01-29
      相关资源
      最近更新 更多