简体   繁体   English

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

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

I know two ways with switch statement to write logic what I want to implement in C#.我知道 switch 语句的两种方法来编写我想在 C# 中实现的逻辑。 They are:他们是:

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");
}

These variants work identically and I know they represent relational pattern.这些变体的工作方式相同,我知道它们代表关系模式。 But is there a difference which variant will I use in my program?但是我将在我的程序中使用哪个变体有区别吗?

The second way will be optimized to do binary search but the first way not (in the current version of compiler).第二种方式将被优化为进行二进制搜索,但第一种方式不会(在当前版本的编译器中)。

It is not so important for switch with three cases, but may improve performance for large switch .对于具有三种情况的switch并不那么重要,但可能会提高大型switch的性能。

The second way is equivalent of something like this, which in the worst case results in two comparisons, in general has O(log(casesCount)) complexity: 第二种方式相当于这样,在最坏的情况下会导致两次比较,通常具有O(log(casesCount))复杂度:

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

The first way checks all conditions sequentially, which in the worst case results in three comparisons, and has linear complexity: 第一种方法顺序检查所有条件,在最坏的情况下会导致三个比较,并且具有线性复杂度:

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

But a much better way to write this switch is to use switch expression rather than statement , much shorter and compiles like the second way:但是编写此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