您当前的位置: 首页 >  c#

光怪陆离的节日

暂无认证

  • 2浏览

    0关注

    1003博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

c#——switch case语句

光怪陆离的节日 发布时间:2022-07-27 11:08:34 ,浏览量:2

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语句的区别:

● 大于等于(>=)、小于等于(            
关注
打赏
1665731445
查看更多评论
0.1525s