空值和重载等于运算符之间的奇怪行为
可能的重复:
C# 可以将值类型与 null 进行比较
为什么值类型为重载相等运算符的DateTime和Decimal可以与空值进行比较吗?
我一直认为值类型是不可为 null 的值,但我可以编写以下代码:
DateTime dateTime = DateTime();
if(dateTime == null)
//do something
编译不会引发异常,但比较始终为 false。
先感谢您。
Possible Duplicate:
C# okay with comparing value types to null
Why value type as DateTime and Decimal whose the equality operator is overloaded can be compared with null value?
I always thought that value types are non-nullables values, but I'm allowed to write the following code:
DateTime dateTime = DateTime();
if(dateTime == null)
//do something
The compilation doesn't throw an exception, however the comparison is always false.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为双方都可以隐式转换为
DateTime?
。这是一个不太理想的极端情况,基本上 :(在某些情况下它会发出警告,但不是针对所有情况(例如,这里不是)。
例如,使用
int
:您将收到此警告:
It's because there's an implicit conversion to
DateTime?
available from both sides. It's a bit of a corner case which isn't ideal, basically :(In some cases it gives a warning, but not for all (so not here, for example).
For example, using
int
:You'll get this warning: