【问题标题】:Strange Behavior of Nested Dictionary in Unity C#Unity C#中嵌套字典的奇怪行为
【发布时间】:2019-09-25 03:51:18
【问题描述】:

我在字典中使用字典。分配的最后一个键值也将存储为所有先前键的值,即使各个键分配不同。我错过了什么吗?

Dictionary<string, Dictionary <int,bool>> seenValsRounds= new Dictionary<string, Dictionary<int, bool>>();

void prepareRoundsVals()
    {       
        Dictionary <int,bool> roundVals = new Dictionary<int, bool> ();
        roundVals.Add (0,false);
        seenValsRounds.Add ("A", roundVals);
        seenValsRounds.Add ("B", roundVals);
        seenValsRounds.Add ("C", roundVals);
        seenValsRounds.Add ("D", roundVals);
        seenValsRounds ["A"] [0] = false;
        seenValsRounds ["B"] [0] = false;
        seenValsRounds ["C"] [0] = false;
        seenValsRounds ["D"] [0] = true;
        foreach (KeyValuePair<string, Dictionary<int,bool>> kvp in seenValsRounds) {            
            Debug.Log(kvp.Key + " in round " + 0 + ": " + seenValsRounds [kvp.Key][0]);     
        }
    }

预期结果: A是假的, B 是假的, C 是假的, D 是真的

实际结果: A 为真, B 为真, C 为真, D 是真的


根据答案和 cmets 的建议在下面解决。每个嵌套字典也应该是“新的”:

        Dictionary <int,bool> roundVals1 = new Dictionary<int, bool> ();
        Dictionary <int,bool> roundVals2 = new Dictionary<int, bool> ();
        Dictionary <int,bool> roundVals3 = new Dictionary<int, bool> ();
        Dictionary <int,bool> roundVals4 = new Dictionary<int, bool> ();
        roundVals1.Add (0,false);
        roundVals2.Add (0,false);
        roundVals3.Add (0,false);
        roundVals4.Add (0,false);
        seenValsRounds.Add ("A", roundVals1);
        seenValsRounds.Add ("B", roundVals2);
        seenValsRounds.Add ("C", roundVals3);
        seenValsRounds.Add ("D", roundVals4);

【问题讨论】:

  • 您将四次添加相同的 Dictionary、roundVals 到 seensValsRounds。在您的代码中,只有两个不同的字典在起作用,因为您只做两个“新”。
  • 你有一个对象。你放在不同的盒子里。将此对象涂成绿色。绿色对象可以在这些框中的任何一个中找到。
  • 有一个基本列表的地方一定有关于 ref 类型和 value 类型的欺骗
  • Eric Lippert gave a great answer 解释 C# 中的引用,这就是您在这里遇到的。我不确定解决您的问题的最佳方法是什么(例如,可能将嵌套字典重构为其他内容?或者只是根据需要克隆/复制字典),但根本原因是 Dictionary 是一种引用类型。跨度>

标签: c# dictionary unity3d nested


【解决方案1】:

那是因为您在 seenValsRounds 字典中放置了对 roundVals 字典对象的相同引用。您应该为 A、B、C 和 D 创建一个新字典。

【讨论】:

    【解决方案2】:

    这可能会有所帮助或嵌套字典替代。

    创建 Sample.cs 脚本并对其进行测试。

     public Dictionary<string,Tuple<string,string,string,int>> _planets = new 
         Dictionary<string, Tuple<string,string, string, int>>();
         void Start()
         {
               string myKey = string.Concat("1","MetalMine","Level");
               if(!_planets.ContainsKey(myKey))
               {
                   _planets.Add(myKey,Tuple.Create("1","MetalMine","Level",0));
               }
               Debug.Log("_planets mykey "+myKey+" ==> "+_planets[myKey].Item4);
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多