表达式Expressions

表达式是在操作数运算符的基础之上构造而成。Expressions are constructed from operands and operators. 表达式的运算符指明了向操作数应用的运算。The operators of an expression indicate which operations to apply to the operands. 运算符的示例包括 +-*/newExamples of operators include +, -, *, /, and new. 操作数的示例包括文本、字段、局部变量和表达式。Examples of operands include literals, fields, local variables, and expressions.

如果表达式包含多个运算符,那么运算符的优先级决定了各个运算符的计算顺序。When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. 例如,表达式 x + y * z 相当于计算 x + (y * z),因为 * 运算符的优先级高于 + 运算符。For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the + operator.

如果操作数两边的两个运算符的优先级相同,那么运算符的结合性决定了运算的执行顺序:When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed:

  • 除了赋值运算符和 null 合并运算符之外,所有二元运算符均为左结合 运算符,即从左向右执行运算。Except for the assignment and null-coalescing operators, all binary operators are left-associative, meaning that operations are performed from left to right. 例如,x + y + z 将计算为 (x + y) + zFor example, x + y + z is evaluated as (x + y) + z.
  • 赋值运算符、null 合并 ????= 运算符和条件运算符 ?: 为右结合 运算符,即从右向左执行运算。The assignment operators, the null-coalescing ?? and ??= operators, and the conditional operator ?: are right-associative, meaning that operations are performed from right to left. 例如,x = y = z 将计算为 x = (y = z)For example, x = y = z is evaluated as x = (y = z).

可以使用括号控制优先级和结合性。Precedence and associativity can be controlled using parentheses. 例如,x + y * z 先计算 yz,并将结果与 x 相加,而 (x + y) * z 则先计算 xy,然后将结果与 z 相乘。For example, x + y * z first multiplies y by z and then adds the result to x, but (x + y) * z first adds x and y and then multiplies the result by z.

大部分运算符可重载Most operators can be overloaded. 借助运算符重载,可以为一个或两个操作数为用户定义类或结构类型的运算指定用户定义运算符实现代码。Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

C# 提供多个运算符用于执行算术逻辑按位和移位运算以及相等排序比较。C# provides a number of operators to perform arithmetic, logical, bitwise and shift operations and equality and order comparisons.

要了解按优先级排序的完整 C# 运算符列表,请参阅 C# 运算符For the complete list of C# operators ordered by precedence level, see C# operators.