我有两个对象(相同类型),其中包含 byte?
类型的 Prop myprop
。属性设置为 null
。当我执行 objectA.myprop.Equals(objectB.myprop)
时,尽管 MSDN 得到的结果是“true”代码示例声明“应用于任何空对象的等于返回 false。”
我猜 C# 使用单独的重载来进行可空类型比较。我想知道在这种情况下,C# 在内部如何处理对象与可空类型。
最佳答案
当你这样调用它时,它会使用 Nullable<T>.Equals(object)
它显示了文档中的预期行为:
(返回值为 true
如果...)
The
HasValue
property is false, and the other parameter isnull
. That is, two null values are equal by definition.
同样通过==
实现平等,C# 4 规范(提升运算符)的第 7.3.7 节指出:
For the equality operators
==
[and]!=
a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.
(强调我的。)
就 object.Equals
的实现而言,这是一般规则:
The following statements must be true for all implementations of the Equals method. In the list, x, y, and z represent object references that are not null.
[...]
x.Equals(null)
returns false.
所以虽然它是一般规则,但它不适用于这种特定情况 - 因为这里的值不是对象 reference - 它是 值类型值。这仍然有些令人惊讶,除非你基本上接受 Nullable<T>
有点特殊 - 它具有特定的 C# 编译器支持并且它在装箱和拆箱方面具有 CLR 支持。
关于c# - 等于与另一个可空类型上的可空类型进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249455/