如何在 C# 8.0 中编写新的 Switch 表达式?

WBOY
发布: 2023-08-25 18:57:02
转载
1473 人浏览过

如何在 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
登录后复制

以上是如何在 C# 8.0 中编写新的 Switch 表达式?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!