确定 .net 中值类型、引用类型和 IList 的对象等效性
我有一个类,其属性名为“Value”,其类型为“对象”。 值可以是任何类型、结构、类、数组、IList 等。
我的问题是 setter 和确定值是否已更改。 这对于值类型来说足够简单,但引用类型和列表却存在问题。
对于一个类,您是否假设 Equals 方法已正确实现,或者只是假设每次调用 setter 时该值都发生了变化? 如果我确实假设它已更改,那么也许我也应该为值类型假设它,以便行为保持一致。
对于列表,我可以检查大小,然后检查集合中的每个项目,看看它们是否已更改。
你们如何处理这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不必通过
这种方式声明,而是
知道 Value 的所有实例都将实现 Equals 方法。因此您可以检查两个实例的相等性。
Instead of having
you could declare
This way you know that all instances of Value will implement the Equals method. Thus you can check equality of two instances.
为什么要关心值是否改变了?是否有理由不能假设每次调用 setter 时值都会发生变化?
如果有充分的技术原因,您始终可以使用泛型并将
Value
设为IEquatable
而不是类型object
。这确保该对象已实现Equals()
方法。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 typeIEquatable<T>
instead of typeobject
. This ensures that the object has implemented theEquals()
method.