if
语句if(condition){// Do something}else{// Do something else}
可以级联使用if
,elseif
,elseif
,elseif
,else
语句:
usingSystem;publicclassIfStatementSample{publicvoidIfMyNumberIs(){intmyNumber=5;if(myNumber==4)Console.WriteLine("This will not be shown because myNumber is not 4.");elseif(myNumber<0){Console.WriteLine("This will not be shown because myNumber is not negative.");}elseif(myNumber%2==0)Console.WriteLine("This will not be shown because myNumber is not even.");else{Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");}}}
switch
语句case
语句必须有跳转语句(break
、goto
、return
)。但可以堆积("stacking")case语句,如下例。如果使用goto
语句,可以跳转到case标签或者default case (例如gotocase0
或gotodefault
)。
default
标签是可选的。
switch(nCPU){case0:Console.WriteLine("You don't have a CPU! :-)");break;case1:Console.WriteLine("Single processor computer");break;case2:Console.WriteLine("Dual processor computer");break;// Stacked casescase3:// falls throughcase4:// falls throughcase5:// falls throughcase6:// falls throughcase7:// falls throughcase8:Console.WriteLine("A multi processor computer");break;default:Console.WriteLine("A seriously parallel computer");break;}
C#允许字符串作为switch变量:
switch(aircraftIdent){case"C-FESO":Console.WriteLine("Rans S6S Coyote");break;case"C-GJIS":Console.WriteLine("Rans S12XL Airaile");break;default:Console.WriteLine("Unknown aircraft");break;}
do...while
loopusingSystem;publicclassDoWhileLoopSample{publicvoidPrintValuesFromZeroToTen(){intnumber=0;do{Console.WriteLine(number++.ToString());}while(number<=10);}}
for
looppublicclassForLoopSample{publicvoidForFirst100NaturalNumbers(){for(inti=0;i<100;i++){System.Console.WriteLine(i.ToString());}}}
foreach
looppublicclassForEachSample{publicvoidDoSomethingForEachItem(){string[]itemsToWrite={"Alpha","Bravo","Charlie"};foreach(stringiteminitemsToWrite)System.Console.WriteLine(item);}}
while
loopusingSystem;publicclassWhileLoopSample{publicvoidRunForAWhile(){TimeSpandurationToRun=newTimeSpan(0,0,30);DateTimestart=DateTime.Now;while(DateTime.Now-start<durationToRun){Console.WriteLine("not finished yet");}Console.WriteLine("finished");}}
break
break语句用于跳出switch语句的case标签,或者跳出for、foreach、while、do .. while循环。
usingSystem;namespaceJumpSample{publicclassEntry{staticvoidMain(string[]args){inti;for(i=0;i<10;i++)// see the comparison, i < 10{if(i>=3){break;// Not run over the code, and get out of loop.// Note: The rest of code will not be executed,// & it leaves the loop instantly}}// Here check the value of i, it will be 3, not 10.Console.WriteLine("The value of OneExternCounter: {0}",i);}}}
continue
continue
语句把控制转移到当次循环的临结束。
usingSystem;namespaceJumpSample{publicclassEntry{staticvoidMain(string[]args){intOneExternCounter=0;for(inti=0;i<10;i++){if(i>=5){continue;// Not run over the code, and return to the beginning// of the scope as if it had completed the loop}OneExternCounter+=1;}// Here check the value of OneExternCounter, it will be 5, not 10.Console.WriteLine("The value of OneExternCounter: {0}",OneExternCounter);}}}
return
namespaceJumpSample{publicclassEntry{staticintFun(){inta=3;returna;// the code terminates here from this functiona=9;// here is a block that will not be executed}staticvoidMain(string[]args){intOnNumber=Fun();// the value of OnNumber is 3, not 9...}}}
yield
yield
关键字用于定义一个迭代块作为一个枚举器产生值。典型作为IEnumerable
接口的方法实现。可写为:
下例在方法MyCounter
中使用yield关键字。该方法定义了一个iterator block,并发挥枚举器对象。
usingSystem;usingSystem.Collections;publicclassYieldSample{publicstaticIEnumerableMyCounter(intstop,intstep){inti;for(i=0;i<stop;i+=step){yieldreturni;}}staticvoidMain(){foreach(intjinMyCounter(10,2)){Console.WriteLine("{0} ",j);}// Will display 0 2 4 6 8}}
throw
可以抛出异常。也可用在catch或finally块中重新抛出异常。
namespaceExceptionSample{publicclassWarrior{privatestringName{get;set;}publicWarrior(stringname){if(name=="Piccolo"){thrownewException("Piccolo can't battle!");}}}publicclassEntry{staticvoidMain(string[]args){try{Warriora=newWarrior("Goku");Warriorb=newWarrior("Vegeta");Warriorc=newWarrior("Piccolo");// exception here!}catch(Exceptione){Console.WriteLine(e.Message);}}}}