首页 文章资讯内容详情

如何在C#8.0中编写新的Switch Expression?

2026-06-04 1 花语

switch表达式在表达式上下文中提供类似switch的语义

switch是一个选择语句,它基于与match表达式匹配的模式从一个候选列表中选择一个要执行的switch部分。

如果针对三个或更多条件测试单个表达式,则switch语句通常用作if-else构造的替代方法。

示例

编写开关的新方法

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