ICollection.Contains on custom types

后端 未结 4 788
旧时难觅i
旧时难觅i 2021-01-12 02:19

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 IC

4条回答
  •  囚心锁ツ
    2021-01-12 03:06

    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.

    To use your own comparison, implement IEqualityComparer (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.Contains method doesn't have the IEqualityComparer overload.)

提交回复
热议问题