如何在 C# 8.0 中編寫新的 Switch 表示式?
在表示式上下文中,switch 表示式提供了類似於 switch 的語義
switch 是一個選擇語句,它根據與匹配表示式的模式匹配,從候選列表中選擇單個 switch 部分來執行。
如果一個單獨的表示式要針對三個或更多條件進行測試,則通常將 switch 語句用作 if-else 結構的替代方法。
示例
編寫 Switch 的新方法
var message = c switch{
Fruits.Red => "The Fruits is red",
Fruits.Green => "The Fruits is green",
Fruits.Blue => "The Fruits is blue"
};示例 1
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
switch (c){
case Fruits.Red:
Console.WriteLine("The Fruits is red");
break;
case Fruits.Green:
Console.WriteLine("The Fruits is green");
break;
case Fruits.Blue:
Console.WriteLine("The Fruits is blue");
break;
default:
Console.WriteLine("The Fruits is unknown.");
break;
}
var message = c switch{
Fruits.Red => "The Fruits is red",
Fruits.Green => "The Fruits is green",
Fruits.Blue => "The Fruits is blue"
};
System.Console.WriteLine(message);
Console.ReadLine();
}
}輸出
The Fruits is green The Fruits is green
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP