Switch是一个选择语句,它基于具有match表达式的模式匹配从一个候选列表中选择一个要执行的switch部分。
如果针对三个或更多条件测试单个表达式,则switch语句通常用作if-else构造的替代方法。
切换语句更快。switch语句比较的平均数将为1,而不管您有多少种不同的情况。因此,任意情况的查找为O(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("水果未知。"); break; } Console.ReadLine(); } Using If else class Program{ public enum Fruits { Red, Green, Blue } public static void Main(){ Fruits c = (Fruits)(new Random()).Next(0, 3); if (c == Fruits.Red) Console.WriteLine("The Fruits is red"); else if (c == Fruits.Green) Console.WriteLine("The Fruits is green"); else if (c == Fruits.Blue) Console.WriteLine("The Fruits is blue"); else Console.WriteLine("水果未知。"); Console.ReadLine(); } }