Unity C#中嵌套词典的奇怪行为

时间:2019-05-07 13:08:21

标签: c# dictionary unity3d nested

我正在词典中使用词典。即使各个键的分配不同,最后分配的键值也将存储为所有先前键的值。我想念什么吗?

@media all\0 {
  .selector { rule: value };
}

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

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


根据答案和评论中的建议解决以下问题。每个嵌套的字典也应该是“新的”:

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]);     
        }
    }

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

它可能有帮助或嵌套字典替代。

创建 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);
     }