[英]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.