亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Unity3D 中寫入嵌套字典

在 Unity3D 中寫入嵌套字典

C#
慕無忌1623718 2021-12-25 16:52:25
我不能直接將值寫入我的嵌套字典嗎?如果我能像這樣訪問它會很好:public Dictionary<string, Dictionary<string, Dictionary<string, int>>> planets =    new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;但我得到:KeyNotFoundException: 字典中不存在給定的鍵。這是否意味著我必須Keys互相插入?
查看完整描述

2 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

這是否意味著我必須依次插入我的密鑰?


是的,您需要按順序初始化每個:


planets[Planet.CharacterId] = new Dictionary<string, Dictionary<string, int>>();

planets[Planet.CharacterId]["MetalMine"] = new Dictionary<string, int>();

planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;

您可以在此處使用集合初始值設定項語法,但這不會使內容更具可讀性和可維護性。


您似乎最好使用一個類,而不是字典的字典:


public class Planet

{

    public List<Mine> Mines { get; set; }

}


public class Mine

{

    public string Type { get; set; }

    public int Level { get; set; }

}


var planets = new Dictionary<string, Planet>();


planets[Planet.CharacterId] = new Planet

{

    Mines = new List<Mine>

    {

        new Mine

        {

            Type = "Metal",

            Level = 0

        }

    };

}


查看完整回答
反對 回復 2021-12-25
?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

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

創建 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);

    }


查看完整回答
反對 回復 2021-12-25
  • 2 回答
  • 0 關注
  • 360 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號