'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)
{
开发者_Python百科 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();
Have your entity class implement IEquatable<T>
.
精彩评论