Modify List.Contains behavior

后端 未结 3 1495
清歌不尽
清歌不尽 2021-01-12 04:23

I have a List with the class MyObj : IComparable. I wrote the method CompareTo in the MyObj class per the

相关标签:
3条回答
  • 2021-01-12 05:09

    According to the documentation for List<T>.Contains, it uses either your implementation of IEquatable interface or object.Equals, that you can override as well.

    0 讨论(0)
  • 2021-01-12 05:21

    Did you try overriding the Equals method?

    List<T>, according to reflector, uses EqualityComparer<T> to check for containment, and the default implementation (ObjectEqualityComparer) uses Equals for most normal objects.

    0 讨论(0)
  • 2021-01-12 05:23

    The absolute easiest way to find out whether your CompareTo method is called is to set a breakpoint in it and hit F5 to run your program. But I believe that List<T>.Contains looks for the IEquatable<T> interface for making the comparison.

    0 讨论(0)
提交回复
热议问题