简体   繁体   中英

Modify List.Contains behavior

I have a List<MyObj> with the class MyObj : IComparable . I wrote the method CompareTo in the MyObj class per the IComparable interface, but when I use the List<MyObj>.Contains(myObjInstance) it returns false when it should be true .

I'm not sure I'm understanding how I need to proceed to make sure the List uses my custom comparison method when calling then Contains function.

Here is my compareTo implementation:

    #region IComparable Members

    public int CompareTo(object obj)
    {
        MyObj myObj = (MyObj)obj;
        return String.Compare(this.Symbol, myObj.Symbol, true);
    }

    #endregion

Note the Symbol property is a string.

To clarify I've put a stopping point in that compareTo method and it doesn't even go in there.

Anyone has ever tried that?

Thanks.

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.

根据该文件List<T>.Contains ,它使用您的任何实施IEquatable接口或object.Equals ,你可以重写为好。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM