簡體   English   中英

為什么 C# switch 語句不能接受“動態”類型?

[英]Why can a C# switch statement not accept the 'dynamic' type?

由於“在編譯時,假定類型為動態的元素支持任何操作” ,我認為這意味着如果我要在switch語句中使用它,編譯器會假定動態變量將是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 那么給了什么? 這種限制的原因是什么?

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

您無法確定編譯時的dynamic變量。

你怎么知道你將在case-label比較哪個值,因為動態變量可以包含任何類型的值。

看這個

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

現在想想你的案例標簽(你將比較哪種類型的價值)

因為case語句必須只包含常量,所以如果你將thing轉換為字符串:

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

因為case語句必須只包含常量。 因此,僅將開關限制為“本機”數據(int,double,float等)和字符串。 Dynamic可以包含各種數據,包括引用類型。

由於 C# 8 您可以為此使用模式匹配開關表達式:

dynamic thing;

thing switch
{
    int intThing => $"it's an int, incremented: {intThing + 1}",
    string stringThing => $"it's a string, uppercase: {stringThing.ToUpper()}",
    _ => "I have no idea what this is"
};

升級你的VS,在VS 2017中,switch語句已經接受了動態類型。

快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM