微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何在 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 表达式?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐