gpt4 book ai didi

c# - Unity C# 中嵌套字典的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:46 25 4
gpt4 key购买 nike

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

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 创建一个新字典。

关于c# - Unity C# 中嵌套字典的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com