.NET 包含自己的相等比较功能,但我不太明白它是如何工作的。
如果所需的 Equals() 和 ==
行为是验证一个对象的每个字段都等于另一个对象的每个字段,是否有必要用一个方法覆盖 Equals()这是明确的吗?
最佳答案
如果您正在使用一个类,那么是的,这是必要的。
对于引用类型(类),.NET 默认情况下提供比较引用本身的相等性比较,而不是类中的值。如果您想要逐个字段进行比较,则需要覆盖 Equals。
对于结构(值类型),默认比较是逐个字段进行比较。
来自 the documentation :
The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.
关于.net - 什么时候需要重写 .NET 类中的 Equals()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993837/