简体   繁体   English

确定.net中值类型,引用类型和IList的对象等效项

[英]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”的属性的类,该类的类型为Object。 Value can be of any type, a structure, a class, an array, IList etc. 值可以是任何类型,结构,类,数组,IList等。

My problem is with the setter and determining whether the value has changed or not. 我的问题是setter和确定值是否已更改。 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? 对于类,您是否假设Equals方法已正确实现,还是仅假设每次调用setter时值都已更改? 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. 这样,您知道Value的所有实例都将实现Equals方法。 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? 为什么不能仅假设每次调用setter时都更改了值,是有原因的吗?

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 . 如果有很好的技术原因,则可以始终使用泛型并使Value的类型为IEquatable<T>而不是object类型。 This ensures that the object has implemented the Equals() method. 这样可以确保对象已实现Equals()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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