簡體   English   中英

帶整數表達式的 switch case

[英]switch case with integer expression

我正在嘗試使用switch case而不是If Else語句,在該語句中我必須首先檢查字符串的長度,並且我必須對其進行處理。

switch (mystring.length)
{
    case <=25:
    {
        //do this
        break;
    }
    case <50:
    {
        //do this
        break;
    }
    default:
        break;
}

這是我想做的事情,但無法獲得如何將<25放在 case 前面,因為根據 switch case 規則,這不合適。

對您的特定情況使用 if/else 總是更好,使用 switch 語句您不能在情況下放置條件。 看起來您正在檢查范圍,如果范圍是恆定的,那么您可以嘗試以下操作(如果您想使用 switch 語句)

int Length = mystring.Length;
int range = (Length - 1) / 25;
switch (range)
{
    case 0:
        Console.WriteLine("Range between 0 to 25");
        break;
    case 1:
        Console.WriteLine("Range between 26 to 50");
        break;
    case 2:
        Console.WriteLine("Range between 51 to 75");
        break;

}

這確實對 OP 沒有太大幫助,但希望它會幫助將來尋找它的人。

如果您使用的是 C# 7(在 Visual Studio 2017 中可用),則可以switch range

例子:

switch (mystring.length)
{
    case int n when (n >= 0 && n <= 25):
    //do this
    break;

    case int n when (n >= 26 && n <= 50 ):
    //do this
    break;
}

您不能使用switch執行此操作,但可能有解決方法。

Dictionary<int, Action> actions = new Dictionary<int, Action>()
    {
        {25,()=>Console.WriteLine("<25")},
        {49,()=>Console.WriteLine("<50")},
        {int.MaxValue,()=>Console.WriteLine("Default")},
    };


actions.First(kv => mystring.length < kv.Key).Value();

試試這個:

int range = (int) Math.Floor(mystring.Length / 25);

switch (range) {
case 0:

    //do this <= 25
    break;

case 1:

    //do this < 50 & > 25
    break;

default:
    break;
}​

暫無
暫無

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

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