zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#——switch case语句

c# 语句 case switch
2023-09-27 14:22:14 时间

c#——switch case语句

c#中的switch case语句有三种结构,具体形式如下图所示:
在这里插入图片描述
(1)Switch的第一种结构:(如例1)

switch(i)

case 1:

//

break;

case2:

//

break;

例1

[csharp] view plaincopyprint?
namespace Switch
{
class Program
{
static void Main(string[] args)
{
int i = 2;
switch(i)
{
case 2:
Console.WriteLine(“你真2!”);
Console.WriteLine(“你真有才!”);
break;
case 4:
Console.WriteLine(“你去死吧!”);
break;
case 8:
Console.WriteLine(“发发发!”);
break;
}
Console.ReadKey();
}
}
}

(2)Switch的第二种结构:

switch(i)

case 1:

//

break;

case2:

//

break;

default:

//

break;

例2

[csharp] view plaincopyprint?
namespace Switch
{
class Program
{
static void Main(string[] args)
{
int i = 9;
switch(i)
{
case 2: //相当于if(if==2)
Console.WriteLine(“你真2!”);
Console.WriteLine(“你真有才!”);
break; //C#中必须写break
case 4:
Console.WriteLine(“你去死吧!”);
break;
case 8:
Console.WriteLine(“发发发!”);
break;
default: //相当于if语句的else
Console.WriteLine(“你输入的{0}没有意义”,i);
break;
}
Console.ReadKey();
}
}
}

注意:C#中的switch语句必须写break,不写不行,但有一种情况除,合并了case情况,可以不写break。(如例3):

Switch的第三种结构:合并了case情况,以省略break.

switch(i)

case 1:

case2:

//

break;

例3:

[csharp] view plaincopyprint?
namespace Switch
{
class Program
{
static void Main(string[] args)
{
int i = 200;
switch(i)
{
case 2: //相当于if(if==2)
Console.WriteLine(“你真2!”);
Console.WriteLine(“你真有才!”);
break; //C#中必须写break
case 4:
Console.WriteLine(“你去死吧!”);
break;
case 8:
Console.WriteLine(“发发发!”);
break;
/*
case 100:
Console.WriteLine(“你输入的是整钱!”);
Console.WriteLine(“你真有钱”);
break;
case 200:
Console.WriteLine(“你输入的是整钱!”);
Console.WriteLine(“你真有钱”);
break;
*/

            //上面的代码等同于下面的代码  
            case 100:  
            case 200:      //相当于if(i=100||i=200),唯一一个case后不用break的情况  
                Console.WriteLine("你输入的是整钱!");  
                Console.WriteLine("你真有钱");  
                break;  


            default:       //相当于if语句的else  
                Console.WriteLine("你输入的{0}没有意义",i);  
                break;  
        }  
        Console.ReadKey();  
    }  
}  

}

注意:switch语句中case 的值只能是用2,4,“aaa” 等常量,不能是变量、表达式。 (如例4)

例4

[csharp] view plaincopyprint?
namespace Switch
{
class Program
{
static void Main(string[] args)
{
string s1 = Console.ReadLine();
int i = Convert.ToInt32(s1);
int k = 10;
switch(k)
{
case i: //错误:case中值只能用2,4,“aaa” 等常量,不能写变量
Console.WriteLine(“你输入的和程序假定的一样!”);
break; //C#中必须写break
}
Console.ReadKey();
}
}
}

总结:switch语句和if语句的区别:

● 大于等于(>=)、小于等于(<=)的判断用if语句,而等于(=)的判断用switch语句。

● switch语句中的case类似于if…else…else if…else,但是离散值的判断。

   (离散值的判断自认为是等于情况的判断)。


● switch一般都可以及用if重写,但是if不一定能用switch重写(如例2)。


● 不要忘了break.C#中break不写是不行的,除了合并case的情况(如例3)。

● case 中的值必须是常量,不能是变量、表达式(如例4)。