简体   繁体   中英

Determining object equivalence for value types, reference types and ILists in .net

I have a class with a Property called 'Value' which is of type Object. Value can be of any type, a structure, a class, an array, IList etc.

My problem is with the setter and determining whether the value has changed or not. This is simple enough for value types, but reference types and lists present a problem.

For a class, would you assume that the Equals method has been implemented correctly, or just assume that the value has changed every time the setter is called? If I did assume it's changed, then perhaps I should assume it for value types as well, so that the behaviour is consistent.

For a list, I could check the size and then every item in the collection to see if they have changed.

How do you guys handle this problem?

Instead of having

object Value

you could declare

IEquatable<T> Value

This way you know that all instances of Value will implement the Equals method. Thus you can check equality of two instances.

Why should you care whether the value has changed or not? Is there a reason why you can't just assume the value changed every time the setter is called?

If there is a good technical reason why, you could always use generics and make your Value of type IEquatable<T> instead of type object . This ensures that the object has implemented the Equals() method.

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