繁体   English   中英

C# 使用这两个开关操作有什么区别?

[英]C# What's the difference between using these two switch operations?

我知道 switch 语句的两种方法来编写我想在 C# 中实现的逻辑。 他们是:

int hour = DateTime.Now.Hour;
string timeWord = string.Empty;

// first
switch (hour)
{
    case int x when hour < 12:
        timeWord = "morning";
        break;
    case int x when hour < 18:
        timeWord = "afternoon";
        break;
    case int x when hour < 24:
        timeWord = "evening";
        break;
    default:
        throw new Exception("Another fine mess you got us into");
}
// second
switch (hour)
{
    case < 12:
        timeWord = "morning";
        break;
    case < 18:
        timeWord = "afternoon";
        break;
    case < 24:
        timeWord = "evening";
        break;
    default:
        throw new Exception("Another fine mess you got us into");
}

这些变体的工作方式相同,我知道它们代表关系模式。 但是我将在我的程序中使用哪个变体有区别吗?

第二种方式将被优化为进行二进制搜索,但第一种方式不会(在当前版本的编译器中)。

对于具有三种情况的switch并不那么重要,但可能会提高大型switch的性能。

第二种方式相当于这样,在最坏的情况下会导致两次比较,通常具有O(log(casesCount))复杂度:

if (hour < 18)
  timeWord = hour < 12 ? "morning" : "afternoon";
else if (hour < 24)
  timeWord = "evening";
else
  throw ...;

第一种方法顺序检查所有条件,在最坏的情况下会导致三个比较,并且具有线性复杂度:

if (hour < 12)
  timeWord = "morning";
if (hour < 18)
  timeWord = "afternoon";
if (hour < 24)
  timeWord = "evening";
else
  throw ...;

但是编写此switch的更好方法是使用switch 表达式而不是语句,更短并且像第二种方式一样编译:

var timeWord = hour switch {
  < 12 => "morning",
  < 18 => "afternoon",
  < 24 => "evening",
  _ => throw new Exception()
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM