开发者

Dictionary<Key,Value> - key cannot be class?

I'm using a Vector3 - contains properties X,Y,Z as a key in a dictionary. Lets say I already added to the dictionary (myDic开发者_开发问答) a Vector3 with values (0,0,0).

Then I do this:

Vector3 vec = new Vector3(0,0,0);
if (!myDic.ContainsKey(vec))
{
    //Should never reach here.
}

I also created overload operators for == and != for the Vector3 class.

It reaches there anyways. Is there a problem when using an object like a Vector3 to be the key for a dictionary?


You need to override GetHashCode and Equals inside your class. The dictionary works on the combination of both, with the first check being the hash and the clincher being Equals. Providing a custom implementation for == is not going to do anything for your dictionary.

If you are unable or unwilling to override these methods within the class itself, your other option is to implement an IEqualityComparer<YourClass> and provide an instance of the implementation in the dictionary constructor. It will be within this implementation that you will provide code for the aforementioned methods.


You are implementing it wrong :)

In short, you need to implement Equals and GetHashCode: == and != are irrelevant here as they are not used.

The reason == and != are not used is that they, like all operators, are non virtual and the "constraint" for the K in IDictionary<K,V> is object (not specified, really). Therefore, only the (virtual) methods valid for all objects (which includes all sub-types of object) such as Equals and GetHashCode can be used in a polymorphic fashion here.

See Example of Dictionary collection with custom class as key? for a working example with test-case.

Happy coding.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜