[C#基本知識] null合併運算符-null條件運算符-switch語句

核心代碼演示:測試

 static void Main(string[] args)
        {
            //1.null合併運算符
            string s1 = null;
            string s2 = s1 ?? "nothing";
            Console.Write(s2);

            //2.null條件運算符(Elvis運算符)
            System.Text.StringBuilder sb = null;
            string s3 = sb?.ToString();
            Console.Write(s3);

            //3.二者結合使用
            System.Text.StringBuilder sb2 = null;
            string s4 = sb2?.ToString() ?? "nothing";
            Console.Write(s4);

            //4.switch 測試
           object x = 2000.0d;
            switch(x)
            {
                case float f when f > 1000.0:
                    Console.WriteLine(" float f when f > 1000");
                    break;
                case double d when d > 1000.0:
                    Console.WriteLine("double d when d > 1000");
                    break;
                case decimal m when m > 1000:
                    Console.WriteLine("decimal m when m > 1000");
                    break;
                case null:
                    Console.WriteLine("Null");
                    break;
                default:
                    Console.WriteLine("Over");
                    break;
            }
            Console.ReadKey();
        }
相關文章
相關標籤/搜索