gpt4 book ai didi

c# - switch 语句是否优于双条件和 fall-through if 语句?

转载 作者:行者123 更新时间:2023-11-30 17:09:01 26 4
gpt4 key购买 nike

当我必须编写多个条件语句时,我通常使用 switch 语句,通常有三个或更多明确定义的条件。

但是,要处理包含失败行为的双条件语句,我经常在简单的if、else if、else 语句和 之间犹豫不决切换语句:

if (condition1)
{
// handling condition1.
}
else if (condition2)
{
// handling condition2.
}
else
{
// handling fall-through.
}

switch (n)
{
case condition1:
// handling condition1.
break;

case condition2:
// handling condition2.
break;

default:
// handling fall-through.
break;
}

Wikipedia Switch statement article状态:

In some languages andprogramming environments, the use of a case or switch statement isconsidered superior to an equivalent series of if-else statementsbecause it is:

  • easier to debug (e.g. setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability)
  • easier to read (subjective)
  • easier to understand and therefore
  • easier to maintain
  • faster execution potential

关于 .NET 公共(public)语言运行时,switch 语句的更快执行潜力在这种情况下是否现实?

我很想知道公共(public)语言运行时如何处理这两种情况,以及一种情况如何优于另一种情况。

最佳答案

更快的执行潜力意味着它尽可能尝试使用二进制搜索(而不是线性搜索,在 if...else if... 情况下)。

但是,if...else if... 通常更强大,因为它可以做 switch 做不到的事情。

所以我想如果您需要做的只是比较字符串或整数,请使用 switch。它还有助于提高可读性。

关于c# - switch 语句是否优于双条件和 fall-through if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com