匿名类型相等 [英] Equality for anonymous types
问题描述
为什么用于比较匿名类型的Equals()和==的语义不同?为什么一个比较值,另一个比较参考?背后的原因是什么?
Why does the semantics of Equals() and == differs when used to compare anonymous types? Why does one compare values and the other compare references? What is the reason behind it?
推荐答案
==
不调用Equals
,而是查找==
重载运算符.由于匿名类型没有重载的==
运算符,因此C#为此使用了引用比较.
==
doesn't call Equals
, it looks for ==
overloaded operator. Since anonymous types doesn't have overloaded ==
operator, so C# uses reference comparison for it.
但是使用Equals
会比较字段值.这就是为什么==
和Equals
之间的结果不同的原因.
But with Equals
it compares field values. That is why the result between ==
and Equals
differ.
因为匿名类型上的Equals和GetHashCode方法是 根据Equals和GetHashCode方法的定义 属性,两个具有相同匿名类型的实例仅相等 如果它们的所有属性都相等.
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
这篇关于匿名类型相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!