如何在 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