2016-10-26 8 views
0

sthを作成する可能性はありますか? PHPのような連想配列のように? 私はいくつかのプレイヤーデータでゲームを作成する予定はありませんが、私は簡単に私が欲しいものをこのように説明できる:C#mimic未知のキー番号の連想配列(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 

私は必要なものはかなっています。私は次のようにアドレスすることができます:

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"; 

しかし、問題は(のみ2つのキーで動作します)ここから:正確にこれを複製することは容易ではないようですので、

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

[辞書](https://msdn.microsoft.com/en-us/library/xfhwa508(V = VS。 110).aspx)が必要なものを持っているはずです。そうでない場合:.net-generic-collectionsはあらゆる目的のためのクラスを持っています。しかし、よりクリーンな方法は、あなたのプレーヤーとそのプロパティを表すクラスを定義することです –

+0

これはPHPと何が関係がありますか? – Epodax

+0

PHPとの関係: "連想配列"はPHPでは存在しますがC#では存在しません。同等。 – Dobi

答えて

1

C#は強く型付けされました動作。

A "可能性":

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