Equality for anonymous types [duplicate]

南楼画角 提交于 2019-12-10 04:27:00

问题


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?


回答1:


== doesn't call Equals, it looks for == overloaded operator. Since anonymous types doesn't have overloaded == operator, so C# uses reference comparison for it.

But with Equals it compares field values. That is why the result between == and Equals differ.

Anonymous Types (C# Programming Guide)

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.



来源:https://stackoverflow.com/questions/23703846/equality-for-anonymous-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!