C#词典-词典中不存在给定的键 [英] C# Dictionary - The given key was not present in the dictionary

查看:310
本文介绍了C#词典-词典中不存在给定的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将Tiled(平铺的地图编辑器)地图文件中的游戏对象加载到我在C#中制作的游戏引擎中.我正在使用TiledSharp(链接到github 此处 ).它使用字典来保存我要加载的每个单独图块(或游戏对象")的属性.但是由于某些原因,当我遍历属性时会收到错误消息,并且如果我检查它是否为空,也会收到错误消息

I'm currently trying to load game objects from a Tiled (Tiled map editor) map file into a game engine I'm making in C#. I'm using TiledSharp (Link to github here). It uses a dictionary to hold properties about each individual tile (or 'game object') I'm trying to load. But for some reason I get an error when I loop through the properties, and I also get an error if I check if it's null

以下是我正在使用的代码的片段:

Here's a snippet of the code I'm using:

for (int l = 0; l < tmxMap.Tilesets[k].Tiles.Count; l++)
    // This line throws an error
    if (tmxMap.Tilesets[k].Tiles[l].Properties != null)
        // and if I remove the above line, this line throws an error
        for (int m = 0; m < tmxMap.Tilesets[k].Tiles[l].Properties.Count; m++)

我得到的错误是字典中不存在给定的键.但是...我什至都不在寻找钥匙.

The error I get says The given key was not present in the dictionary. But... I'm not even checking for a key.

我想念什么吗?

任何帮助将不胜感激.

推荐答案

我得到的错误是字典中不存在给定的键.但是...我什至都不在寻找钥匙.

The error I get says The given key was not present in the dictionary. But... I'm not even checking for a key.

是的,您正在检查密钥.这是您的代码:

Yes you are checking for a key. This is your code:

if (tmxMap.Tilesets[k].Tiles[l].Properties != null)

您正在使用键k检查Tilesets,然后通过键l检查Tiles.如果Tilesets不包含键为k的项目,则会出现该错误.对于使用键lTiles,也是如此.

You are checking for Tilesets with key k and then checking Tiles with key l. If the Tilesets does not contain an item with key k, you will get that error. The same is true for Tiles with key l.

使用字典时,您可以执行以下操作:

You can do the following when working with dictionaries:

选项1

查找执行两次:一次查看该项目是否存在,然后第二次获取值:

The lookup is performed twice: once to see if the item exists, and then a second time to get the value:

var items = new Dictionary<string, string>();
items.Add("OneKey", "OneValue");
if(items.ContainsKey("OneKey"))
{
    var val = items["OneKey"];
}

选项2

这是查找一次的另一种方法:

And here is another approach where the lookup is performed once:

string tryVal;
if (items.TryGetValue("OneKey", out tryVal))
{
    // item with key exists so you can use the tryVal
}

这篇关于C#词典-词典中不存在给定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆