C Sharp/Control
< C Sharp
條件分支語句
編輯if
語句
編輯
if (condition)
{
// Do something
}
else
{
// Do something else
}
可以級聯使用if
, else if
, else if
, else if
, else
語句:
using System;
public class IfStatementSample
{
public void IfMyNumberIs()
{
int myNumber = 5;
if ( myNumber == 4 )
Console.WriteLine("This will not be shown because myNumber is not 4.");
else if( myNumber < 0 )
{
Console.WriteLine("This will not be shown because myNumber is not negative.");
}
else if( 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 (例如 goto case 0
或 goto default
)。
default
標籤是可選的。
switch (nCPU)
{
case 0:
Console.WriteLine("You don't have a CPU! :-)");
break;
case 1:
Console.WriteLine("Single processor computer");
break;
case 2:
Console.WriteLine("Dual processor computer");
break;
// Stacked cases
case 3:
// falls through
case 4:
// falls through
case 5:
// falls through
case 6:
// falls through
case 7:
// falls through
case 8:
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
loop
編輯
using System;
public class DoWhileLoopSample
{
public void PrintValuesFromZeroToTen()
{
int number = 0;
do
{
Console.WriteLine(number++.ToString());
} while(number <= 10);
}
}
for
loop
編輯
public class ForLoopSample
{
public void ForFirst100NaturalNumbers()
{
for (int i = 0; i < 100; i++)
{
System.Console.WriteLine(i.ToString());
}
}
}
foreach
loop
編輯
public class ForEachSample
{
public void DoSomethingForEachItem()
{
string[] itemsToWrite = {"Alpha", "Bravo", "Charlie"};
foreach (string item in itemsToWrite)
System.Console.WriteLine(item);
}
}
while
loop
編輯
using System;
public class WhileLoopSample
{
public void RunForAWhile()
{
TimeSpan durationToRun = new TimeSpan(0, 0, 30);
DateTime start = DateTime.Now;
while (DateTime.Now - start < durationToRun)
{
Console.WriteLine("not finished yet");
}
Console.WriteLine("finished");
}
}
跳轉語句
編輯break
編輯
break語句用於跳出switch語句的case標籤,或者跳出for、foreach、while、do .. while循環。
using System;
namespace JumpSample
{
public class Entry
{
static void Main(string[] args)
{
int i;
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
語句把控制轉移到當次循環的臨結束。
using System;
namespace JumpSample
{
public class Entry
{
static void Main(string[] args)
{
int OneExternCounter = 0;
for (int i = 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
編輯
namespace JumpSample
{
public class Entry
{
static int Fun()
{
int a = 3;
return a; // the code terminates here from this function
a = 9; // here is a block that will not be executed
}
static void Main(string[] args)
{
int OnNumber = Fun();
// the value of OnNumber is 3, not 9...
}
}
}
yield
編輯
yield
關鍵字用於定義一個迭代塊作為一個枚舉器產生值。典型作為IEnumerable
接口的方法實現。可寫為:
- yield ::= "yield" "return" expression
- yield ::= "yield" "break"
下例在方法MyCounter
中使用yield關鍵字。該方法定義了一個iterator block,並發揮枚舉器對象。
using System;
using System.Collections;
public class YieldSample
{
public static IEnumerable MyCounter(int stop, int step)
{
int i;
for (i = 0; i < stop; i += step)
{
yield return i;
}
}
static void Main()
{
foreach (int j in MyCounter(10, 2))
{
Console.WriteLine("{0} ", j);
}
// Will display 0 2 4 6 8
}
}
throw
編輯
可以拋出異常。也可用在catch或finally塊中重新拋出異常。
namespace ExceptionSample
{
public class Warrior
{
private string Name { get; set; }
public Warrior(string name)
{
if (name == "Piccolo")
{
throw new Exception("Piccolo can't battle!");
}
}
}
public class Entry
{
static void Main(string[] args)
{
try
{
Warrior a = new Warrior("Goku");
Warrior b = new Warrior("Vegeta");
Warrior c = new Warrior("Piccolo"); // exception here!
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}