简体   繁体   中英

'Contains' method returns false

I've got some strange issue.

I've an EntityCollection< T > which contains an element but the Contains method returns false.

I've overriden T's 'Equals' method but the 'Contains' method does not call it (while it's said so in documentation).

When I do foreach (T x in coll) , x.Equals(element) returns true.

Thanks for the help.

code:

contains(object entCol, object val)
    {
        var coll = (ICollection<GraphicSockets>)entCol;
        var socket = val as GraphicSockets;
        foreach (GraphicSockets sock in coll)
            socket.Equals(sock); //true for first element, GraphicSocket's Equals function called
        coll.Contains(socket);//false, Equals function not called}

the code i'd actually like to use is

private static bool contains(object entCol, object val)
    {
        Type entColType = typeof(EntityCollection<>).MakeGenericType(val.GetType());
        MethodInfo contains = entColType.GetMethod("Contains");
        return (bool)contains.Invoke(entCol, new object[] { val });
    }

this worked once but stopped when i started using wcf, i wonder how this contains method works.....

Does your problem go away if you use:

    public override int GetHashCode()
    {
        return 0;
    }

Note this is just a debugging test, not a suggestion for real


Now that we know this is the problem, let me explain.

Your object has a strong identity (Equals) and a weak identity (GetHashCode). The GetHashCode identity can be thought as a bin number. These idenitites must not change after they are inserted into a hash table, otherwise the hash table operations stop working correctly. By having GetHashCode() return 0, I gave it the weakest of all idenitites, "everyone is in the same bin", but it did not change.

Note that GetHashCode() is just a performance enhancement, if you are happy with the performance, you are done. If not, another simple hashcode is to exor all comparisons that are in used in the Equal method. Something like:

return LastName.GetHashCode() ^ FirstName.GetHashCode();

Remember GetHashCode() is an performance enhancment, do not spend too much time computing it. Maybe in the above case, the following might have been a better perfoming hashcode:

return LastName.GetHashCode();

让你的实体类实现IEquatable<T>

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