[英]KeyNotFoundException: The given key was not present in the dictionary
I am sorry if this question is being asked because i missed something incredibly basic. 如果有人问这个问题,我感到很抱歉,因为我错过了一些难以置信的基本知识。
I am getting KeyNotFoundException: The given key was not present in the dictionary from Unity for a search for a Dictionary Key. 我收到KeyNotFoundException:从Unity 字典中找不到给定的键,无法搜索字典键。 Yet throughout my (still quite small) project i am successfully using MapLocation in other Dictionarys as a Key 但是在我的整个项目(仍然很小)中,我成功地将其他词典中的MapLocation用作键
I have stripped the code down to basics. 我已将代码简化为基本内容。
public class SpriteManager : MonoBehaviour {
Dictionary<MapLocation, GameObject> SpriteDictionary;
void Start(){
SpriteDictionary = new Dictionary<MapLocation, GameObject>();
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
//Create Location Data
MapLocation mLoc = new MapLocation(x, y);
//Create GameObjects
GameObject go = new GameObject();
SpriteDictionary.Add(mLoc, go);
}
}
MapLocation mTest = new MapLocation(0,1);
Debug.Log("Dictionary entry exists?: " + SpriteDictionary.ContainsKey(mTest));
}
At the end the mTest of MapLocation(0,1) Debug line is giving me a false . 最后,MapLocation(0,1)Debug行的mTest给了我false 。
Here is the MapLocation code for completion. 这是完成的MapLocation代码。
using UnityEngine;
using System.Collections;
[System.Serializable]
public class MapLocation {
public int x;
public int y;
public MapLocation(){}
public MapLocation(int x, int y){
this.x = x;
this.y = y;
}
}
You have to override GetHashCode()
and Equals(object obj)
of MapLocation, for example: 您必须重写MapLocation的GetHashCode()
和Equals(object obj)
,例如:
public override bool Equals(object obj)
{
MapLocation m = obj as MapLocation;
return m == null ? false : m.x == x && m.y == y;
}
public override int GetHashCode()
{
return (x.ToString() + y.ToString()).GetHashCode();
}
Inside YourDictionary.ContainsKey(key)
and YourDictionary[key]
, use GetHashCode()
and Equals(object obj)
to judge equivalent. 在YourDictionary.ContainsKey(key)
和YourDictionary[key]
,使用GetHashCode()
和Equals(object obj)
来判断等效项。 Reference 参考
deyu note is correct, when using custom types as the key in a dictionary, you must define GetHashCode
and Equals
. deyu note是正确的,当在字典中使用自定义类型作为键时,必须定义GetHashCode
和Equals
。 For interest, I've include alternative hashing algorithms. 出于兴趣,我提供了其他哈希算法。
The existing Point
class calculates the hash as follows: 现有Point
类的哈希计算如下:
public override int GetHashCode()
{
return this.x ^ this.y;
}
Using ReSharper code completion: 使用ReSharper代码完成:
public override int GetHashCode()
{
unchecked
{
return (this.x * 397) ^ this.y;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.