在C#中使用if / else和switch-case有什么区别?
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();
}
}热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短