C#switch语句的默认标签如何处理可为空的枚举?

C#switch语句的默认标签如何处理一个可为空的枚举?

默认标签是否可以捕获空值以及任何未处理的情况?

如果它是空的,它将打到默认标签。

public enum YesNo { Yes, No, } public class Program { public static void Main(string[] args) { YesNo? value = null; switch (value) { case YesNo.Yes: Console.WriteLine("Yes"); break; case YesNo.No: Console.WriteLine("No"); break; default: Console.WriteLine("default"); break; } } } 

该程序将打印default

除非null被处理。

 public class Program { public static void Main(string[] args) { YesNo? value = null; switch (value) { case YesNo.Yes: Console.WriteLine("Yes"); break; case YesNo.No: Console.WriteLine("No"); break; case null: Console.WriteLine("NULL"); break; default: Console.WriteLine("default"); break; } } } 

打印NULL

如果以后添加了未处理的枚举值:

 public enum YesNo { Yes, No, FileNotFound, } public class Program { public static void Main(string[] args) { YesNo? value = YesNo.FileNotFound; switch (value) { case YesNo.Yes: Console.WriteLine("Yes"); break; case YesNo.No: Console.WriteLine("No"); break; default: Console.WriteLine("default"); break; } } } 

它仍然打印default

您可以使用空合并运算符??null开关值路由到除default的特定情况标签:

 public static IEnumerable<String> AsStrings(this IEnumerable<Char[]> src) { Char[] rgch; var e = src.GetEnumerator(); while (e.MoveNext()) { switch ((rgch = e.Current)?.Length ?? -1) { case -1: // <-- value when e.Current is 'null' yield return null; break; case 0: yield return String.Empty; break; case 1: yield return String.Intern(new String(rgch[0], 1)); break; default: // 2...n yield return new String(rgch); break; } } }