List.Contains不工作的希望 [英] List.Contains is not working as hoped

查看:140
本文介绍了List.Contains不工作的希望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有类型的对象 MyBull 列表与LT; MyBull>原稿

  //只是一个例子
MyBull X = getMeTheObjectWithIdFromDB(9);orig.add(X);//再一次一样吗?数据对象
MyBull Y = getMeTheObjectWithIdFromDB(9);

这是为什么假呢?

  //这是错误的,即使所有属性
// x和y是相同的。
orig.Contains< MyBull>(Y);


解决方案

在默认情况下的对象将基于暴露参考平等。如果你想基于ID字段的自定义规则,如平等,你需要重写等于 GetHash code 方法。

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); 

解决方案

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 and GetHashCode methods.

这篇关于List.Contains不工作的希望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆