首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 特殊運算子總覽:三元條件、遞增遞減、new、typeof、checked/unchecked

     編輯:關於C#

特殊運算子分類

三元條件運算子 ?:


condition ? exprIfTrue : exprIfFalse;

// 範例
string result = score >= 60 ? "Pass" : "Fail";
int max = a > b ? a : b;

// 巢狀 (建議改用 if-else 提升可讀性)
var grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";

// 型別必須相容 (隱含轉換)
object obj = flag ? 1 : "text"; // int 與 string 隱含轉換為 object

遞增遞減運算子 ++ / --


int i = 0;
// 前綴:先運算,回傳新值
Console.WriteLine(++i); // 1
// 後綴:先回傳舊值,再運算
Console.WriteLine(i++); // 1 (i 變 2)

// 陷阱:同一運算式多次修改同一變數 → 未定義行為 (C# 有定義但難讀)
int x = 1;
int y = x++ + ++x; // 避免這種寫法

new 運算子多重面向

運算子分類用途
?:三元條件單行條件運算式
++, --遞增/遞減整數/指標/列舉加減 1
new物件建立/型別建構實例化、陣列建立、泛型建構、匿名型別
typeof型別資訊編譯期取得 System.Type
checked, unchecked溢位控制整數運算溢位檢測開關

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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
用法範例
建立類別實例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() { } (非覆寫)