如果有人问这个问题,我很抱歉,因为我错过了一些非常基本的东西。
我在 Unity 中搜索字典键时收到KeyNotFoundException:字典中不存在给定的键。 然而,在我的(仍然很小)的项目中,我成功地使用其他词典中的 MapLocation 作为键
我已将代码简化为基础内容。
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));
}
最后,MapLocation(0,1) 调试行的 mTest 给了我一个 false。
这是用于完成的 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;
}
}
最佳答案
您必须重写 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();
}
在YourDictionary.ContainsKey(key)
和YourDictionary[key]
内部,使用GetHashCode()
和Equals(object obj)
判断等价。 Reference
关于c# - KeyNotFoundException : The given key was not present in the dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953978/