简体   繁体   English

运算符重载和优先级

[英]Operator overloading and precedence

In C# you can overload operators, eg + and * . 在C#中,您可以重载运算符,例如+* In their mathematical interpretation, these operators have a well defined order of precedence. 在他们的数学解释中,这些算子具有明确的优先顺序。

Is this order kept when overloading, does it change in some deterministic way, or can you overload the order of precedence as well? 重载时是否保留此顺序,是否以某种确定性方式更改,或者您是否也可以重载优先顺序?

If you overload an operator, it will always take precedence over the default implementation. 如果重载运算符,它将始终优先于默认实现。 However, you can't change the precedence of the operator itself, so it will be kept as default. 但是,您无法更改运算符本身的优先级,因此它将保留为默认值。 More information on MSDN . 有关MSDN的更多信息。

Relevant quotes: 相关报价:

User-defined operator implementations always take precedence over predefined operator implementations: Only when no applicable user-defined operator implementations exist will the predefined operator implementations be considered. 用户定义的运算符实现始终优先于预定义的运算符实现:仅当不存在适用的用户定义的运算符实现时,才会考虑预定义的运算符实现。

and

User-defined operator declarations cannot modify the syntax, precedence, or associativity of an operator. 用户定义的运算符声明不能修改运算符的语法,优先级或关联性。 For example, the / operator is always a binary operator, always has the precedence level specified in Section 7.2.1 , and is always left-associative. 例如,/运算符始终是二元运算符,始终具有第7.2.1节中指定的优先级,并且始终是左关联的。

Overloading does not change precedence. 重载不会改变优先级。

Operator precedence is set by the compiler, and cannot be changed, at least not without customizing the compiler. 运算符优先级由编译器设置,并且不能更改,至少在没有自定义编译器的情况下也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM