在c#中使用switch语句和if/else语句的优缺点是什么?除了代码的外观,我无法想象有这么大的区别。

是否有任何原因导致最终的IL或相关的运行时性能会有根本的不同?

相关:什么是更快,开关上字符串或elseif上类型?


当前回答

题外话,但我经常担心(更经常看到)if/else和switch语句用太多的情况变得太大。这些通常会损害可维护性。

常见的罪魁祸首包括:

在多个if语句中执行太多操作 案例陈述多得人类无法分析 if求值中的条件太多,以至于不知道要寻找什么

修复:

提取到方法重构。 使用带有方法指针的Dictionary而不是大小写,或者使用IoC来增加可配置性。方法工厂也很有帮助。 提取条件到自己的方法

其他回答

有三个理由支持这种转变:

A compiler targeting native code can often compile a switch statement into one conditional branch plus an indirect jump whereas a sequence of ifs requires a sequence of conditional branches. Depending on the density of cases a great many learned papers have been written about how to compile case statements efficiently; some are linked from the lcc compiler page. (Lcc had one of the more innovative compilers for switches.) A switch statement is a choice among mutually exclusive alternatives and the switch syntax makes this control flow more transparent to the programmer then a nest of if-then-else statements. In some languages, including definitely ML and Haskell, the compiler checks to see if you have left out any cases. I view this feature as one of the major advantages of ML and Haskell. I don't know if C# can do this.

一个趣闻:在托尼·霍尔接受终身成就奖的演讲中,我听到他说,在他职业生涯中所做的所有事情中,有三件事是他最自豪的:

发明快速排序 发明switch语句(Tony称之为case语句) 开始和结束他的工业生涯

我无法想象没有开关的生活。

通常它看起来会更好——也就是更容易理解发生了什么。考虑到性能上的好处最少,代码的视图是最重要的区别。

因此,如果if/else看起来更好,就使用它,否则使用switch语句。

在阅读了我面前所有的答案并浏览了所有的网页之后,我可以说switch case语句可以帮助您使您的代码看起来更整洁和易于管理。当我在我的项目中测试时,性能也比else if语句好,因为我必须检查超过10个用例(这可能听起来很奇怪!)

我认为Switch比If条件更快 看看是否有这样一个程序:

写一个程序,输入任意数字(1- 99之间),并检查它在哪个槽a) 1- 9,然后槽1 b) 11 - 19,然后槽2 c) 21-29,然后槽3,直到89-99

然后,如果你有许多条件,但儿子切换情况下,你必须只是类型

开关(no /10) case 0 = 1-9,case 1 = 11-19,以此类推

这将是如此简单

还有很多这样的例子!

switch语句基本上是相等的比较。键盘事件比switch语句有很大的优势,当代码易于编写和阅读时,if elseif语句会,缺少{括号}也可能会带来麻烦。

char abc;
switch(abc)
{
case a: break;
case b: break;
case c: break;
case d: break;
}

如果(theAmountOfApples大于5 && theAmountOfApples小于10)保存苹果,则使用if elseif语句非常适合多个解决方案 否则如果(theAmountOfApples大于10 || theAmountOfApples == 100)出售你的苹果。我不会写c#或c++,但我在学习java之前学过它,它们是很接近的语言。