开发者

How does Dictionary<T> work with key objects that don't implement Equals and GetHashCode?

If I place a key object in an Dictionary that doesn't implement Equals and GetHashCode how does the Dictionary ContainsKey w开发者_如何学JAVAork? By checking the references are equal?

Thanks


The base Object class implements Equals and GetHashCode. All classes inherit from Object by default. The dictionary will just use these implementations.

The default implementation of Equals tests object references, which will probably be fine in most cases for your dictionary.

The base implementation of GetHashCode is fairly naive, in fact even the documentation states:

The default implementation of the GetHashCode method does not guarantee unique return values for different objects.

So the recommendation is to override it yourself if you intend to use an object as a dictionary or hashtable key.

With regards to how this works. Remember that GetHashCode isn't actually critical for the implementation of a dictionary. hash codes are allowed to clash, that is kind of the point. The hash code is just used to help with locating an object, is it the equality test that will be used to check the object is the correct one in the end. Lets just say for arguments sake that every object just returned a hash code of 1. They would all end up in the same pot in the dictionary, probably in some fairly random order (perhaps inserted order) and it would just fall back to using Equals to verify the object identity. It wouldn't be efficient, but it would work fine.

So, if you are looking for efficiency, you should consider overriding GetHashCode, but if it's just going to be a small dictionary and efficiency isn't too important, you'll be fine just to leave it with the default.

[All the usual considerations apply. It's best not override GetHashCode for mutable objects, and make 100% sure that objects that return true for Equals() return the same hash code.]


It uses the Object.GetHashCode implementation, but note that this hash code is not an object identity:

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

If you want to have your dictionary operate on reference equality, you can use the following comparer when constructing your dictionary:

class ReferenceComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T x, T y)
    {
        return object.ReferenceEquals(x, y);
    }

    public int GetHashCode(T obj)
    {
        return obj.GetHashCode();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜