Nullable< T> ;:和重载运算符,布尔? &布尔 [英] Nullable<T>: and overloaded operators, bool? & bool
问题描述
- 为什么为布尔定义了运算符&,而没有为运算符&&定义?
- 这到底如何1)布尔? &布尔?和2)布尔?和布尔工作?
在Nullable上还有其他有趣的运算符语义吗?任何泛型T的重载运算符?
Any other "interesting" operator semantics on Nullable? Any overloaded operators for generic T?
推荐答案
Nullable< T>
是解除运算符。这意味着什么:如果T有运算符,T?
Operators on Nullable<T>
are "lifted" operators. What this means is: if T has the operator, T? will have the "lifted" counterpart.
&&和||并不是与&和-例如,它们不能被重载-根据ECMA规范14.2.2运算符重载:
&& and || aren't really operators in the same sense as & and | - for example, they can't be overloaded - from the ECMA spec 14.2.2 Operator overloading:
可重载的二进制运算符为:
+-* /%& | ^<< >> ==!=>< > =< =只有上面列出的运算符可以重载
。特别是,不可能
重载成员访问权限,
方法调用或=,&&,||,
??,?:,选中,未选中,新
The overloadable binary operators are: + - * / % & | ^ << >> == != > < >= <= Only the operators listed above can be overloaded. In particular, it is not possible to overload member access, method invocation, or the =, &&, ||, ??, ?:, checked, unchecked, new, typeof, as, and is operators.
同样,根据ECMA规范,14.2.7解除了运算符,解除运算符的是:
Likewise, from the ECMA spec, 14.2.7 Lifted operators, the lifted operators are:
对于一元运算符
+ ++--! 〜
For the unary operators + ++ - -- ! ~
对于二进制运算符
+-* /%& | ^<< >>
For the binary operators + - * / % & | ^ << >>
对于相等运算符
==!=
For the equality operators == !=
对于关系运算符< >< => =
For the relational operators < > <= >=
因此,基本上,短路运算符未定义为提升运算符。
So basically, the short-circuiting operators aren't defined as lifted operators.
-
提升运算符:编译器提供
Nullable< T>
,基于T的运算符-例如:int
+运算符被解除在int?
上定义为:
Lifted operator: a compiler provided operator on
Nullable<T>
, based on the operators of T - for example: theint
"+" operator gets "lifted" ontoint?
, defined as:
(int?x,int?y)=>(x。 HasValue& y.HasValue)吗? (x.Value + y.Value):(int?)null;
(int? x, int? y) => (x.HasValue && y.HasValue) ? (x.Value + y.Value) : (int?) null;
运算符重载:为给定类型提供自定义运算符实现的操作;例如十进制
和 DateTime
提供各种运算符重载
Operator overloading: the act of providing a custom operator implementation for a given type; for example decimal
and DateTime
provide various operator overloads
短路:& 和
|| 的正常行为(在许多语言中,包括C ++和C#)-即第二个操作数可能不被评估-即
Short-circuiting: the normal behavior of &&
and ||
(in many languages, including C++ and C#) - i.e. the second operand might not be evaluated - i.e.
(expression1,expression2)=> expression1()吗? expression2():false;
(expression1, expression2) => expression1() ? expression2() : false;
或者也许是一个更简单的示例:
Or perhaps a simpler example:
bool someFlag = Method1() && Method2();
如果 Method1()
返回false,则 Method2()
不会执行(因为编译器已经知道总体答案是错误的)。如果 Method2()
有副作用,这一点很重要,因为保存到数据库...
if Method1()
returns false, then Method2()
isn't executed (since the compiler already knows that the overall answer is false). This is important if Method2()
has side-effects, since as saving to the database...
这篇关于Nullable< T> ;:和重载运算符,布尔? &布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!