繁体   English   中英

C#Dictionary - 字典中没有给定的键

[英]C# Dictionary - The given key was not present in the dictionary

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

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

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++)

我得到的错误说字典中没有给定的密钥。 但是......我甚至没有检查钥匙。

我错过了什么吗?

任何帮助,将不胜感激。

我得到的错误说字典中没有给定的密钥。 但是......我甚至没有检查钥匙。

是的,你正在检查钥匙。 这是你的代码:

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

您正在使用密钥k检查Tilesets ,然后使用密钥l检查Tiles 如果Tilesets不包含带有键k的项,则会出现该错误。 具有键l Tiles也是如此。

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

选项1

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

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

选项2

这是另一种执行查找的方法:

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

在我的代码中我可以看到,我认为Tiles是一个字典,当你尝试通过tmxMap.Tilesets[k].Tiles[l]进行迭代时,它会抛出错误,因为它搜索键l,而不是l元素。

你可以试试tmxMap.Tilesets[k].Tiles[tmxMap.Tilesets[k].Tiles.Keys.ElementAt(l)]

您正在尝试根据键kl获取值。

if (tmxMap.Tilesets[k].Tiles[l].Properties != null)语句基本上是获取与Tilesets字典中的k键对应的值。 如果Tilesets字典不包含键k的值,则抛出异常。 此外,如果没有对应于l键的值,则在Tiles字典中,将抛出异常。

您可以使用TryGetValue扩展方法,如果找到该项,它将为您提供值。

    TileSet ts = null;

    if(tmxMap.Tilesets.TryGetValue(k, out ts)
    {
       for (int l = 0; l < ts.Tiles.Count; l++)
       { 
          Tiles tl = null;

          if(ts.TryGetValue(l,out tl)
          {
            if (tl.Properties != null)
            {
              for (int m = 0; m < tl.Properties.Count; m++)
              {
               //Do something
              }
            }
          }
        }
     }

暂无
暂无

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

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