List.Contains 未按预期工作
如果我有一个 MyBull
类型的对象和一个 List
:
// Just an example
MyBull x = getMeTheObjectWithIdFromDB(9);
orig.add(x);
// Again same? data object
MyBull y = getMeTheObjectWithIdFromDB(9);
那为什么这是假的呢?
// This is false, even though all the properties
// of x and y are the same.
orig.Contains<MyBull>(y);
If I have an object of type MyBull
and a List<MyBull> orig
:
// Just an example
MyBull x = getMeTheObjectWithIdFromDB(9);
orig.add(x);
// Again same? data object
MyBull y = getMeTheObjectWithIdFromDB(9);
Why is this false then?
// This is false, even though all the properties
// of x and y are the same.
orig.Contains<MyBull>(y);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认情况下,对象将公开基于引用的相等性。如果您需要自定义规则,例如基于 id 字段的相等性,则需要重写
Equals
和GetHashCode
方法。By default objects will expose reference based equality. If you want custom rules, such as equality based on id fields, you need to override the
Equals
andGetHashCode
methods.如果您可以使用 LINQ 那么您可以
...
If you can use LINQ then you can
...
这是因为 MyBull 实例是通过引用进行比较的。从 .NET 的角度来看,x 和 y 都是不同的实例,因此不等于。
为了解决这个问题,您必须 覆盖 Equals和 GetHashCode 方法(这意味着您应该实现
IEquatable< ;MyBull>
并覆盖 == 和 != 运算符)。This is because the MyBull instances are being compared by reference. From the point of view from .NET, x and y are both different instances and therefore not Equal.
In order to get around this you will have to override the Equals and GetHashCode methods (which means you should probably implement
IEquatable<MyBull>
and override the == and != operators too).您的 MyBull 对象是否实现了 IEquatable.Equals? 两个对象的相等性
此方法将确定OP 请求的
。您的 MyBull 类将实现 IEquatable
,然后您需要重写
Equals
方法,正如 David Neale 在下面提到的,这是当您比较相同类型的对象时(您本身就是这样),最好使用该方法。重写 Object.Equals 和 Object.GetHashCode 也可以。
Does your MyBull object implement
IEquatable<T>.Equals
? This method will determine the equality of two objectsrequested by OP
Your MyBull class would implement IEquatable
and then you would need to override the
Equals
methodAs David Neale mentions below, this is best used when you're comparing objects of the same type--which you are. Overriding Object.Equals and Object.GetHashCode will work too.