C# 語法學習_Lesson 4

C# 語法學習_Lesson 4

陳述式

程式的動作是藉由陳述式來表達。 C# 支援數種不同類型的陳述式,也包含一些內嵌陳述式。

「區塊」可允許單一陳述式或多個陳述式內容。 區塊是指在 { 與 } 分隔符號之間撰寫的陳述式所組成。

  • 「宣告陳述式」可用來宣告區域變數和常數。
1
2
3
4
5
6
7
8
9
10
11
12
static void Declarations(string[] args)
{
//區域變數陳述式
int a;
int b = 2, c = 3;
a = 1;
Console.WriteLine(a + b + c);
//常數陳述式
const float pi = 3.1415927f;
const int r = 25;
Console.WriteLine(pi * r * r);
}
  • 「運算式陳述式」可用來評估運算式。 可用來作為陳述式的運算式包括方法叫用、使用 new 運算子的物件配置、使用 = 和複合指派運算子的指派、使用 ++ 和 – 運算子的遞增和遞減運算,以及 await 運算。
1
2
3
4
5
6
7
8
static void Expressions(string[] args)
{
int i;
i = 123; // Expression statement
Console.WriteLine(i); // Expression statement
i++; // Expression statement
Console.WriteLine(i); // Expression statement
}
  • 「選取陳述式」可用來根據某個運算式的值選取執行對應的陳述式。 在此群組中的是 if 和 switch 陳述式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
static void IfStatement(string[] args)
{
//if 陳述式
if (args.Length == 0)
{
Console.WriteLine("No arguments");
}
else
{
Console.WriteLine("One or more arguments");
}

//switch 陳述式
int n = args.Length;
switch (n)
{
case 0:
Console.WriteLine("No arguments");
break;
case 1:
Console.WriteLine("One argument");
break;
default:
Console.WriteLine($"{n} arguments");
break;
}
}
  • 「重覆運算陳述式」可用來重複執行內嵌的陳述式。 在此群組中的是 while、do、for 及 foreach 陳述式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
static void WhileStatement(string[] args)
{
//while 陳述式
int i = 0;
while (i < args.Length)
{
Console.WriteLine(args[i]);
i++;
}

// do while 陳述式
string s;
do
{
s = Console.ReadLine();
Console.WriteLine(s);
} while (!string.IsNullOrEmpty(s));

// for 陳述式
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
}

// foreach 陳述式
foreach (string s in args)
{
Console.WriteLine(s);
}
}

「跳躍陳述式」可用來轉移控制項。 在此群組中的是 break、continue、goto、throw、return 及 yield 陳述式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
static void BreakStatement(string[] args)
{
// break
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrEmpty(s))
break; //跳出迴圈
Console.WriteLine(s);
}

// continue
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("/"))
continue;
Console.WriteLine(args[i]);
}

// goto
int i = 0;
goto check;
loop:
Console.WriteLine(args[i++]);
check:
if (i < args.Length)
goto loop;


}

// return
static int Add(int a, int b)
{
return a + b;
}
static void ReturnStatement(string[] args)
{
Console.WriteLine(Add(1, 2));
return;
}

//yield
static System.Collections.Generic.IEnumerable<int> Range(int start, int end)
{
for (int i = start; i < end; i++)
{
yield return i;
}
yield break;
}
static void YieldStatement(string[] args)
{
foreach (int i in Range(-10,10))
{
Console.WriteLine(i);
}
}

try…catch 陳述式可用來攔截在執行區塊時發生的例外狀況,而 try…finally 陳述式則可用來指定不論是否發生例外狀況都一律會執行的最終處理程式碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
static double Divide(double x, double y) 
{
if (y == 0)
throw new DivideByZeroException();
return x / y;
}
static void TryCatch(string[] args)
{
try
{
if (args.Length != 2)
{
throw new InvalidOperationException("Two numbers required");
}
double x = double.Parse(args[0]);
double y = double.Parse(args[1]);
Console.WriteLine(Divide(x, y));
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Good bye!");
}
}

checked 和 unchecked 陳述式可用來控制整數型別算術運算和轉換的溢位檢查內容。

1
2
3
4
5
6
7
8
9
10
11
12
static void CheckedUnchecked(string[] args) 
{
int x = int.MaxValue;
unchecked
{
Console.WriteLine(x + 1); // Overflow
}
checked
{
Console.WriteLine(x + 1); // Exception
}
}

lock 陳述式可用來取得所指定物件的互斥鎖定、執行陳述式,然後釋放鎖定。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Account
{
decimal balance;
private readonly object sync = new object();
public void Withdraw(decimal amount)
{
lock (sync)
{
if (amount > balance)
{
throw new Exception(
"Insufficient funds");
}
balance -= amount;
}
}
}

using 陳述式可用來取得資源、執行陳述式,然後處置該資源。
以下列出可供使用的陳述式類型,並提供每個陳述式的範例。

1
2
3
4
5
6
7
8
9
static void UsingStatement(string[] args) 
{
using (TextWriter w = File.CreateText("test.txt"))
{
w.WriteLine("Line one");
w.WriteLine("Line two");
w.WriteLine("Line three");
}
}