# C# 運算子 (C# 參考)C# operators (C# reference)

C# 提供許多由內建類型支援的運算子。C# provides a number of operators supported by the built-in types. 舉例來說，以數值運算元執行算術運算的算術運算子，以及以布林運算元執行邏輯運算的布林值邏輯運算子For example, arithmetic operators perform arithmetic operations with numeric operands and Boolean logical operators perform logical operations with the bool operands. 部分運算子可以多載Certain operators can be overloaded. 進行運算子多載時，您可以為使用者定義類型指定運算元的運算子行為。With operator overloading, you can specify the operator behavior for the operands of a user-defined type.

## 運算子優先順序Operator precedence

var a = 2 + 2 * 2;
Console.WriteLine(a); //  output: 6


var a = (2 + 2) * 2;
Console.WriteLine(a); //  output: 8


+x, -x, !x, ~x, ++x, --x, ^x, (T)x, await, &x, *x, true and false 一元Unary
x.。yx..y RangeRange

ShiftShift

x & y
x ^ y
x | y
x && yx && y 條件式 ANDConditional AND
x || yx || y 條件式 ORConditional OR
x ?? yx ?? y Null 聯合運算子Null-coalescing operator
c ? t : fc ? t : f 條件運算子Conditional operator

## 運算子關聯性Operator associativity

• 左向關聯運算子會依由左至右的順序進行評估。Left-associative operators are evaluated in order from left to right. 除了指派運算子null 聯合運算子 ?? 以外，所有二元運算子都是靠左關聯。Except for the assignment operators and the null-coalescing operator ??, all binary operators are left-associative. 例如，a + b - c 會判斷值為 (a + b) - cFor example, a + b - c is evaluated as (a + b) - c.
• 右向關聯運算子會依由右至左的順序進行評估。Right-associative operators are evaluated in order from right to left. 指派運算子、null 聯合運算子 ??條件運算子 ?: 是右向關聯。The assignment operators, the null-coalescing operator ??, and the conditional operator ?: are right-associative. 例如，x = y = z 會判斷值為 x = (y = z)For example, x = y = z is evaluated as x = (y = z).

int a = 13 / 5 / 2;
int b = 13 / (5 / 2);
Console.WriteLine(\$"a = {a}, b = {b}");  // output: a = 1, b = 6


## 運算元評估Operand evaluation

a + b a，b，+a, b, +
a + b * c a，b，c，*，+a, b, c, *, +
a / b + c * d a，b，/，c，d，*，+a, b, /, c, d, *, +
a / (b + c) * d a，b，c，+，/，d，*a, b, c, +, /, d, *