Intereting Posts

C # mimic ассоциативный массив неизвестного номера ключа (как в PHP)

Есть ли возможность создать sth. как ассоциативный массив, как в PHP? Я не планирую создавать игру с некоторыми игровыми данными, но я мог бы легко объяснить, что я хочу:

player["Name"] = "PName"; player["Custom"]["Gender"] = "Female"; player["Custom"]["Style"] = "S1"; player["Custom"]["Face"]["Main"] = "FM1"; player["Custom"]["Face"]["Eyes"] = "FE1"; player["Custom"]["Height"] = "180"; 

Также длина должна быть динамичной , я не знаю, сколько ключей будет:

 player["key1"]["key2"]=value player["key1"]["key2"]["key3"]["key4"]...=value 

То, что мне нужно, это sth. Я мог бы обратиться так:

 string name = player["Name"]; string gender = player["Custom"]["Gender"]; string style = player["Custom"]["Style"]; string faceMain = player["Custom"]["Face"]["Main"]; string faceEyes = player["Custom"]["Face"]["Eyes"]; string height = player["Custom"]["Height"]; 

Или в некотором роде похоже на это.

То, что я пробовал до сих пор:

 Dictionary<string, Hashtable> player = new Dictionary<string, Hashtable>(); player["custom"] = new Hashtable(); player["custom"]["Gender"] = "Female"; player["custom"]["Style"] = "S1"; 

Но проблема начинается здесь (работает только с двумя клавишами):

 player["custom"]["Face"] = new Hashtable(); player["Custom"]["Face"]["Main"] = "FM1"; 

C # строго типизирован, поэтому не так просто воспроизвести это точное поведение.

Возможность" :

 public class UglyThing<K,E> { private Dictionary<K, UglyThing<K, E>> dicdic = new Dictionary<K, UglyThing<K, E>>(); public UglyThing<K, E> this[K key] { get { if (!this.dicdic.ContainsKey(key)) { this.dicdic[key] = new UglyThing<K, E>(); } return this.dicdic[key]; } set { this.dicdic[key] = value; } } public E Value { get; set; } } 

Применение :

  var x = new UglyThing<string, int>(); x["a"].Value = 1; x["b"].Value = 11; x["a"]["b"].Value = 2; x["a"]["b"]["c1"].Value = 3; x["a"]["b"]["c2"].Value = 4; System.Diagnostics.Debug.WriteLine(x["a"].Value); // 1 System.Diagnostics.Debug.WriteLine(x["b"].Value); // 11 System.Diagnostics.Debug.WriteLine(x["a"]["b"].Value); // 2 System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c1"].Value); // 3 System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c2"].Value); // 4