簡體   English   中英

如何在 C# 中的 switch 表達式中創建一個空的默認情況?

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

如何在 C# 中的 switch 表達式中創建一個空的默認情況?

我說的是這個語言特性。

這是我正在嘗試的:

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

另外,我嘗試不使用逗號:

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

它仍然不想編譯。 所以,我試圖放置一個空函數:

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

它仍然不起作用。

與所有表達式一樣,switch表達式必須能夠計算出一個值。

出於您的目的,switch語句是正確的構造:

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

確切地說,您正在研究表達式switch表達式。 所有表達式都必須返回一個 Console.WriteLine的類型為void返回任何內容

要擺弄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);
}

或將表達式放入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