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" };
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
以上是如何在 C# 8.0 中编写新的 Switch 表达式?的详细内容。更多信息请关注PHP中文网其他相关文章!