| 用法 | 範例 |
| 建立類別實例 | new Person(), new Person("Name") |
| 建立陣列 | new int[10], new int[] {1,2,3}, new int[2,3] |
| 建立委派 | new Action(Foo), new Func(x => x*2) |
| 匿名型別 | new { Name = "A", Age = 20 } |
| 泛型型別參數建構 (new constraint) | T Create() where T : new() => new T(); |
| 隱藏繼承成員 | public new void Foo() { } (非覆寫) |
typeof 運算子
Type t1 = typeof(int);
Type t2 = typeof(List);
Type t3 = typeof(Dictionary<,>); // 開放泛型
// typeof vs GetType()
typeof(string) == "hello".GetType() // true
// typeof: 編譯期常數、靜態型別
// GetType(): 執行期、實際執行個體型別
checked / unchecked 運算子 (溢位控制)
// 運算式形式
int a = checked(2000000000 + 2000000000); // 拋出 OverflowException
int b = unchecked(2000000000 + 2000000000); // 截斷回繞
// 區塊形式
checked {
int c = int.MaxValue + 1; // 拋出
}
unchecked {
int d = int.MaxValue + 1; // 截斷
}
// 受影響運算:++、--、- (負號)、+ - * /、顯式整數轉換
// 不影響:浮點數、decimal、邏輯運算、位移
運算子優先序 (高→低,節選)
1. Primary: x.y, f(x), a[x], x++, x--, new, typeof, checked, unchecked
2. Unary: +, -, !, ~, ++x, --x, (T)x
3. Multiplicative: *, /, %
4. Additive: +, -
...
13. Conditional AND: &&
14. Conditional OR: ||
15. Null-coalescing: ??
16. Ternary: ?:
17. Assignment: =, +=, -=...
總結
掌握這五類特殊運算子:?: 簡化條件賦值、++/-- 區分前後綴語意、new 多重建構用途、typeof 靜態型別資訊、checked/unchecked 溢位控制開關。注意運算子優先序避免隱性 Bug。
- 上一篇文章: C# if 語句完整指南:布林條件、巢狀結構、懸空 Else 與常見錯誤
- 下一篇文章: C# checked 與 unchecked 運算子深度解析:溢位檢測控制、常數與非常數差異、方法邊界限制
Copyright ©
程式碼之家 All Rights Reserved