核心代码演示:
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(); }