简体   繁体   中英

Comparing two objects .

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

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:

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

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).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM