简体   繁体   English

如何在 C# 中的 switch 表达式中创建一个空的默认情况?

[英]How to make an empty default case in switch expression in C#?

How to make an empty default case in switch expression in C#?如何在 C# 中的 switch 表达式中创建一个空的默认情况?

I am talking about this language feature.我说的是这个语言特性。

Here is what I am trying:这是我正在尝试的:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ => ,
        };
    }
}

Also, I tried without the comma:另外,我尝试不使用逗号:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ =>
        };
    }
}

Still it does not want to compile.它仍然不想编译。 So, I tried to put an empty function:所以,我试图放置一个空函数:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ => {}
        };
    }
}

And it still does not work.它仍然不起作用。

A switch expression must be able to evaluate to a value, as with all expressions.与所有表达式一样,switch表达式必须能够计算出一个值。

For your purpose, a switch statement is the correct construct:出于您的目的,switch语句是正确的构造:

int i = -2;
switch (i)
{
    case -1:
        Console.WriteLine("foo");
        break;
    case -2:
        Console.WriteLine("bar");
        break;
}

You are studing expressions switch expressions to be exact.确切地说,您正在研究表达式switch表达式。 All expressions must return a value ;所有表达式都必须返回一个 while Console.WriteLine being of type void returns nothing .Console.WriteLine的类型为void返回任何内容

To fiddle with switch expressions you can try要摆弄switch表达式,您可以尝试

public static void Main() {
  int i = -2;

  // switch expression: given i (int) it returns text (string)
  var text = i switch {
    -1 => "foo",
    -2 => "ignore",
     _ => "???" // or default, string.Empty etc.
  };

  Console.WriteLine(text);
}

Or putting expression into WriteLine :或将表达式放入WriteLine

public static void Main() {
  int i = -2;

  // switch expression returns text which is printed by WriteLine  
  Console.WriteLine(i switch {
    -1 => "foo",
    -2 => "ignore",
     _ => "???"
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM