【发布时间】: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