ICollection的< T>。载自定义类型 [英] ICollection<T>.Contains on custom types

查看:128
本文介绍了ICollection的< T>。载自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个(参考 - 什么关系呢?)类型的的MyType 的不覆盖的等于的方法,有什么启发将确定何时使用,如果一个的ICollection&其中; MyType的> 的包含该类型的给定实例

If I have a (reference - does it matter?) type MyType which does not override the Equals method, what heuristics will be used when determining if an ICollection<MyType> contains a given instance of the type?

什么是用我自己的启发式的最佳方式(如检查的平等的编号的属性值)?

What's the best way to use my own heuristics (e.g. check for the equality of the Id property value)?

推荐答案

由于你的类型没有重载equals,等号的缺省实现将被使用,即引用相等。因此,包含将是真实的,如果集合包含的这很实例的。

Because your type doesn't override Equals, the default implementation of Equals will be used, i.e. reference equality. So Contains will be true if the collection contains that very instance.

要使用自己的比较,实施的IEqualityComparer&LT; T&GT; (如比较IDS),并通过你的比较器的实例到包含方法。 (这里假设你能够使用LINQ的扩展,作为本土的ICollection&LT; T&GT;。载方法不具备的IEqualityComparer过载)

To use your own comparison, implement IEqualityComparer<T> (e.g. to compare the Ids) and pass an instance of your comparer into the Contains method. (This assumes you are able to use LINQ extensions, as the "native" ICollection<T>.Contains method doesn't have the IEqualityComparer overload.)

这篇关于ICollection的&LT; T&GT;。载自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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