2014-01-15 32 views
3

由於'At compile time, an element that is typed as dynamic is assumed to support any operation',我認爲這將意味着如果我在switch語句中使用它,編譯器會認爲動態變量是switch語句支持的類型。爲什麼C#switch語句不能接受'動態'類型?

出乎我的想法,聲明

dynamic thing = "thing"; 
switch (thing) { 
    case "thing": { 
     Console.WriteLine("Was a thing."); 
     Console.ReadKey(); 
     break; 
    } 
    default: { 
     Console.WriteLine("Was not thing."); 
     Console.ReadKey(); 
     break; 
    } 
} 

給人的編譯時錯誤:A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type。那麼是什麼給了?這種限制的原因是什麼?

+0

因爲「case:」關鍵字需要值literal/constant。什麼是動態文字? – elgonzo

+0

因爲在編譯時必須知道要切換的類型。動態值在編譯時不知道,只在運行時才知道。 – danludwig

+0

爲什麼'switch((string)thing)'因爲你明確已經知道類型是什麼? –

回答

3

因爲case-labels中使用的常量必須是與控制類型兼容的編譯時間常量。

在編譯時你不會確定dynamic變量。

您會如何知道您將從哪個值中比較case-label,因爲動態變量可以保存任何類型的值。

看這個

dynamic thing = "thing"; 
//and some later time `thing` changed to 
thing = 1; 

現在想想你的情況標籤(在這種類型的值,就會比較)

+0

如果你要引用一些內容,你應該引用該引用的來源。 – Servy

0

因爲case語句只能包含常量。因此,僅將開關限制爲「本地」數據(int,double,float等)和字符串。 Dynamic可以容納包括參考類型的各種數據。

2

因爲case語句必須包含唯一不變的,如果你施放的事情到字符串:

dynamic thing = "thing"; 
    switch ((string)thing) { 
     case "thing": { 
      Console.WriteLine("Was a thing."); 
      Console.ReadKey(); 
      break; 
     } 
     default: { 
      Console.WriteLine("Was not thing."); 
      Console.ReadKey(); 
      break; 
     } 
    } 
+0

+1創造力......此外,永遠不要這樣做! – sircodesalot

+0

同意......但只是試圖展示如何讓它工作。 –

+0

他想知道不允許它的原因是什麼,而不是如何解決它。這不是問題的答案。 –

相關問題