C# 比较两个对象。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/411232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:19:50  来源:igfitidea点击:

Comparing two objects .

c#

提问by leora

If i have a complex object, what is the best practice pattern to write code to compare 2 instances to see if they are the same

如果我有一个复杂的对象,编写代码来比较 2 个实例以查看它们是否相同的最佳实践模式是什么

采纳答案by Ray Booysen

Implement the IEquatable interface. This defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances. Don't forget to override Equals(object) as well. More information here:

实现 IEquatable 接口。这定义了一个通用方法,值类型或类实现该方法以创建用于确定实例相等性的特定于类型的方法。不要忘记覆盖 Equals(object) 。更多信息在这里:

http://msdn.microsoft.com/en-us/library/ms131187.aspx

http://msdn.microsoft.com/en-us/library/ms131187.aspx

回答by tvanfosson

I think the answer is highly problem dependent. For example, you may want to consider objects equal only if all of their properties are equivalent. This would perhaps be the case where each object doesn't have a uniquely identifying property. If there is such a property (or properties), say an ID or ID and Version, that uniquely identifies each object of the type, then you may only want to compare based on that property (or properties).

我认为答案高度依赖于问题。例如,您可能希望仅当对象的所有属性都相等时才考虑对象相等。这可能是每个对象没有唯一标识属性的情况。如果有这样一个属性(或多个属性),比如 ID 或 ID 和版本,它唯一地标识了该类型的每个对象,那么您可能只想根据该属性(或多个属性)进行比较。

The base pattern, however, ought to be something like:

然而,基本模式应该是这样的:

if their references are equal (includes both null)
   return true
else if one object is null
   return false
else
   return value based on relevant properties

Note that if you override the Equals operator, you'll also want to override GetHashCode() so that the hash codes for equivalent objects are the same. This will ensure that data structures that use the hash code for determining duplicate keys work properly when the object is used as a key.

请注意,如果您覆盖 Equals 运算符,您还需要覆盖 GetHashCode() 以便等效对象的哈希代码相同。这将确保使用哈希码确定重复键的数据结构在对象用作键时正常工作。

回答by Sathish

Since you mentioned a Complex Object, make sure that all composite Objects in the Complex Object implement equals(Object) as mentioned by tvanfosson. Finally implement equals in the Complex object taking advantage of the equals of all composite Objects

既然你提到了一个复杂对象,请确保复杂对象中的所有复合对象都实现了 tvanfosson 提到的 equals(Object)。最后在 Complex 对象中实现 equals,利用所有复合对象的 equals