System.Object
1. 主要運算式: x.y, x[...], x(...), new, typeof, checked, unchecked
2. 一元運算子: +, -, !, ~, ++, --, (T)x, await
3. 乘除: *, /, %
4. 加減: +, -
5. 位移: <<, >>
6. 關係/型別測試: <, >, <=, >=, is, as
7. 相等: ==, !=
8. 邏輯 AND: &
9. 邏輯 XOR: ^
10. 邏輯 OR: |
11. 條件 AND: &&
12. 條件 OR: ||
13. Null 聯合: ??
14. 條件: ?:
15. 指派: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
16. Lambda: =>
關聯性:多為左結合,指派/條件/Null聯合為右結合。
| 類型 | 語法 | 特性 | 範例 |
|---|---|---|---|
| 隱含轉換 | 自動 | 無資訊遺失、不拋例外 | int → long, Derived → Base |
| 明確轉換 | (T)x | 可能遺失/失敗、可拋例外 | double → int, Base → Derived |
| 使用者定義 | implicit/explicit operator | 自訂型別間轉換 | Celsius ↔ Fahrenheit |
| 協助方法 | Convert.ToXxx, Parse, TryParse | 字串/物件轉基本型別 | int.Parse("42") |
checked { int x = int.MaxValue + 1; } // 拋 OverflowException
unchecked { int y = int.MaxValue + 1; } // 環繞 -2147483648
// 預設由專案設定決定 (通常 unchecked)
if/else:布林條件switch:模式比對、字串、列舉、整數while:前置條件do-while:後置條件for:計數器控制foreach:集合迭代 (唯讀)break:離開迴圈/switchcontinue:下一次迭代goto:標籤/case/defaultreturn:離開方法throw:拋出例外
try {
// 可能拋出例外的程式碼
}
catch (FileNotFoundException ex) {
// 特定例外處理
}
catch (IOException ex) when (ex.HResult == 0x80070020) {
// 條件捕獲 (C# 6+)
}
catch (Exception ex) {
// 通用處理
}
finally {
// 確定執行清理碼
}
[Serializable]
public class BusinessException : Exception {
public string ErrorCode { get; }
public BusinessException(string code, string message) : base(message)
=> ErrorCode = code;
protected BusinessException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { }
}
Main 為進入點ref、out、in、paramsyield return)、非同步 (async/await)
using System;
class MethodDemo {
public static void MyMethod() {
Console.WriteLine("這是一個方法");
}
public static int Main() {
Console.WriteLine("Main 也是方法");
MyMethod();
return 0;
}
}
CTS 奠定跨語言型別互通基礎。運算子優先序決定運算式求值順序。型別轉換需注意溢出與資訊遺失。流程控制提供結構化程式設計基礎。例外處理以 try/catch/finally 確保資源清理。方法是程式碼組織基本單位,全屬於型別內部。