簡體   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