C# 带整数表达式的 switch case

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13927815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:07:14  来源:igfitidea点击:

switch case with integer expression

c#.net

提问by neerajMAX

i am trying to use switch caseinstead of If Elsestatement, in which i have to first check length of string and as per that i have to make cases of it.

我正在尝试使用switch case而不是If Else语句,在该语句中我必须首先检查字符串的长度,并且我必须对其进行处理。

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

This is some thing i want to do but unable to get how to put <25in front of case because it is not appropriate as per switch case rules.

这是我想做的一些事情,但无法获得如何放在<25案例前面,因为根据 switch case 规则,这不合适。

采纳答案by Habib

Its always better to use if/else for your particular case, With switch statement you can't put conditions in the case. It looks like you are checking for ranges and if the range is constantthen you can try the following (if you want to use switch statement).

对您的特定情况使用 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;

}

回答by I4V

You can not do this with switchbut there may be a workaround for this.

你不能这样做,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();

回答by pala?н

Try this:

尝试这个:

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

回答by Steve Gomez

This really doesn't help the OP much, but hopefully it will help someone looking for this in the future.

这确实对 OP 没有太大帮助,但希望它会帮助将来寻找它的人。

If you're using C# 7 (Available in Visual Studio 2017), you can switchon a range.

如果您使用的是 C# 7(在 Visual Studio 2017 中可用),则可以switch在范围内使用.

Example:

例子:

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