在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();
}
}热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短