c# - KeyNotFoundException : The given key was not present in the dictionary

标签 c# dictionary unity-game-engine

如果有人问这个问题,我很抱歉,因为我错过了一些非常基本的东西。

我在 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/

相关文章:

c# - 显示非线程安全任务的 “Please Wait”对话框

c# - 日期时间转换和解析 DateTime.Now.ToString ("MM/dd/yyyy hh:mm:ss.fff")

javascript - Topojson 比例问题

c# - unity www "aborted"错误

c# - 当客户端尝试连接到未运行的 C# 服务器时 Unity 卡住

c# - 尝试启动进程时出错

c# - Visual Studio 2015 表示 'cast is redundant' 。为什么?

python - 从元组列表创建字典列表

python - 按字母顺序从字典中返回值

iphone - 使用 Unity for iPhone 进行游戏开发