在 C# 中计算 Switch 语句中的表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1554689/
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-06 18:47:46  来源:igfitidea点击:

Evaluate Expressions in Switch Statements in C#

c#switch-statement

提问by priyanka.sarkar

I have to implement the following in a switchstatement:

我必须在switch声明中实现以下内容:

switch(num)
{
  case 4:
    // some code ;
    break;
  case 3:
    // some code ;
    break;
  case 0:
    // some code ;
    break;
  case < 0:
    // some code ;
    break;
}

Is it possible to have the switch statement evaluate case < 0? If not, how could I do that?

是否可以让 switch 语句求值case < 0?如果没有,我怎么能那样做?

采纳答案by Jon Skeet

You can't - switch/case is only for individual values. If you want to specify conditions, you need an "if":

您不能 - switch/case 仅适用于单个值。如果要指定条件,则需要一个“if”:

if (num < 0)
{
    ...
}
else
{
    switch(num)
    {
        case 0: // Code
        case 1: // Code
        case 2: // Code
        ...
    }
}

回答by Maximilian Mayerl

You will have to use if, wether you want or not. Switch is only capable of comparing your value to constant values.

无论您是否愿意,您都必须使用 if。Switch 只能将您的值与常量值进行比较。

回答by queen3

If your num can't be less than zero:

如果您的 num 不能小于零:

public int GetSwitch(int num) { return num < 0 ? -1 : num; }
switch(GetSwitch(num))
{
case 4: // some code ; break;
case 3:// some code ; break;
case 0: // some code ; break;
case -1 :// some code ; break;
}

If it can, use some other "non-existent" number such as int.MinValue.

如果可以,请使用其他一些“不存在”的数字,例如 int.MinValue。

回答by Oliver Hanappi

The only way I could think of (and I really don't recommand it), would be as follows:

我能想到的唯一方法(我真的不推荐它)如下:

int someValue;

switch (Math.Max(someValue, -1))
{
    case -1:
        // will be executed for everything lower than zero.
        break;

    case 0:
       // will be executed for value 0.
       break;

    case 1:
       // will be executed for value 1.
       break;

    default:
       // will be executed for anything else.
       break;
}

回答by tbreffni

You could do something like this at the end of your switch statement:

你可以在 switch 语句的末尾做这样的事情:

default:
    if(num < 0)
    {
        ... // Code
    }
    break;

回答by StampedeXV

The other way around would be possible also (relating to Jon Skeet's answer):

另一种方式也是可能的(关于 Jon Skeet 的回答):

switch(num)
{
  case a:
      break;
  default:
      if( num < 0 )
      {}
   break;
}

回答by rsp

You cannot use comparisons in switches like you could in VB, you have 2 options here, replace the value you switch on with a known value and use that or - if you mean all other cases - you can use the default clause:

您不能像在 VB 中那样在开关中使用比较,这里有 2 个选项,用已知值替换您打开的值并使用该值,或者 - 如果您指的是所有其他情况 - 您可以使用 default 子句:

switch(num)
{
  case 4:
    // some code ;
    break;
  case 3:
    // some code ;
    break;
  case 0:
    // some code ;
    break;
  default:
    // some code ;
    break;
}

Note that this does not exactly like you asked for: any values other than 0,3,4 will end up in the deafult: clause.

请注意,这并不完全符合您的要求:除 0,3,4 以外的任何值都将出现在 deafult: 子句中。

回答by Max

I know that this topic is pretty old but if someone still looking for the answer now in C# 7 it's possible. Here is an example:

我知道这个话题已经很老了,但如果有人现在仍在 C# 7 中寻找答案,那是可能的。下面是一个例子:

switch (value)
{
     case var expression when value < 0:
         //some code
         break; 

     case var expression when (value >= 0 && value < 5):
         //some code
         break;

     default:
         //some code
         break;
}

回答by Sturla

What you could do is to use a delegate like this.

您可以做的是使用这样的委托。

        var actionSwitch = new Dictionary<Func<int, bool>, Action>
        {
             { x => x < 0 ,     () => Log.Information("less than zero!")},
             { x => x == 1,     () => Log.Information("1")},
             { x => x == 2,     () => Log.Information("2")},
             { x => x == 3,     () => Log.Information("3")},
             { x => x == 4,     () => Log.Information("4")},
             { x => x == 5,     () => Log.Information("5")},
        };

        int numberToCheck = 1;

        //Used like this
        actionSwitch.FirstOrDefault(sw => sw.Key(numberToCheck)).Value();

Just swap out what you wan′t to perform where the Log.Information("x") is and you have your "switch" statement.

只需换出您不想在 Log.Information("x") 所在的位置执行的操作,您就有了“switch”语句。

You will need to some error handling if you check for a key that is "found" by the Func.

如果您检查 Func“找到”的键,您将需要进行一些错误处理。

If you like to see the Func version of the switch I just wrote a blog post with Switch example chapter.

如果您喜欢查看开关的 Func 版本,我刚刚写了一篇包含开关示例章节博客文章

But if you can use C# 7 it will give you better switch capabilities.

但是,如果您可以使用 C# 7,它将为您提供更好的切换功能

回答by Cat_img.jpeg

you can do this

你可以这样做

switch (mark)
{
    case int n when n >= 80:
        Console.WriteLine("Grade is A");
        break;

    case int n when n >= 60:
        Console.WriteLine("Grade is B");
        break;

    case int n when n >= 40:
        Console.WriteLine("Grade is C");
        break;

    default:
        Console.WriteLine("Grade is D");
        break;
}