Loading

Switch表达式

1.旧的用法

        static void Main(string[] args)
        {
            Console.WriteLine(OldMethod("Add"));
            Console.ReadLine();
        }


        private static string OldMethod(string str)
        {
            switch (str)
            {
                case "Add":
                    return "新增";
                case "Upd":
                    return "修改";
                case "Del":
                    return "删除";
                default:
                    return "Null";
            }
        }

2.C#8.0的Switch表达式

        static void Main(string[] args)
        {
            Console.WriteLine(NewMethod("Ins"));
            Console.ReadLine();
        }

      
        private static string NewMethod(string str)
        {
            return str switch
            {
                "Add" => "新增",
                "Upd" => "修改",
                "Del" => "删除",
                _ => throw new ArgumentException("Involid Value", "str")
            };
        }

3.优化Switch表达式

  • default 替换成弃元符号。
  • 方法体中只有一个return和 { },可以替换成 =>(箭头符号)
private static string NewMethod(string str)
=> str switch
{
    "Add" => "新增",
    "Upd" => "修改",
    "Del" => "删除",
     _ => throw new ArgumentException("Involid Value", "str")
};

4.微软官方解释

ArgumentException方法

Switch表达式

posted @ 2022-08-24 16:47  DotNeter-Hpf  阅读(99)  评论(0编辑  收藏  举报