繁体   English   中英

KeyNotFoundException:字典中不存在给定的键

[英]KeyNotFoundException: The given key was not present in the dictionary

如果有人问这个问题,我感到很抱歉,因为我错过了一些难以置信的基本知识。

我收到KeyNotFoundException:从Unity 字典中找不到给定的键,无法搜索字典键。 但是在我的整个项目(仍然很小)中,我成功地将其他词典中的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)Debug行的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)来判断等效项。 参考

deyu note是正确的,当在字典中使用自定义类型作为键时,必须定义GetHashCodeEquals 出于兴趣,我提供了其他哈希算法。

现有Point类的哈希计算如下:

public override int GetHashCode()
{
  return this.x ^ this.y;
}

使用ReSharper代码完成:

public override int GetHashCode()
{
  unchecked
  {
    return (this.x * 397) ^ this.y;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM