c# - 等于与另一个可空类型上的可空类型进行比较

标签 c#

我有两个对象(相同类型),其中包含 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 is null. 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/

相关文章:

c# - 内存是如何在int数组中分配的

c# - 这个请求是由 EF Core buggy 生成的还是我的代码?

c# - ASP.net Javascript 回传

c# - 将多个文件/文件夹从 Windows 资源管理器传递到外部应用程序

c# - 何时使用委托(delegate)而不是接口(interface)

c# - 如何声明所需类型以避免 ".. Ambigious reference.."

C# 通过反射获取属性

c# - 如何以编程方式从值中删除/添加复合/非复合百分比和固定金额?

c# - 将BackgroundWorker转换为具有模态显示的Task.Run

c# - 为什么不能设置循环算法的索引值?