开发者

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

开发者 https://www.devze.com 2022-12-09 19:44 出处:网络
I have a class with a Property cal开发者_运维问答led \'Value\' which is of type Object. Value can be of any type, a structure, a class, an array, IList etc.

I have a class with a Property cal开发者_运维问答led '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.

0

精彩评论

暂无评论...
验证码 换一张
取 消