[英]Strange Behavior of Nested Dictionary in Unity C#
我在字典中使用字典。 分配的最后一个键值也被存储为所有先前键的值,即使各个键分配不同。 我错过了什么吗?
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 为真
根据答案和评论中的建议解决了以下问题。 每个嵌套字典也应该是“新的”:
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);
那是因为您将相同的引用放在了 seenValsRounds 字典中的 roundVals 字典对象中。 您应该为 A、B、C 和 D 创建一个新字典。
创建 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.