doufang7385 2016-10-26 12:50
浏览 102
已采纳

C#模仿未知键号的关联数组(如在PHP中)

Is there a possibility to create sth. like an associative array like in PHP? I don't plan to create a game with some player-data, but I could easily explain this way what I want:

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

Also the length has to be dynamic, I don't how many keys there will be:

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

What I need is sth. I could address like:

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

Or in some way similar to this.

What I tried till now:

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

But the problem starts here (only works with 2 keys):

player["custom"]["Face"] = new Hashtable();
player["Custom"]["Face"]["Main"] = "FM1";
  • 写回答

1条回答 默认 最新

  • douge7771 2016-10-26 16:42
    关注

    C# is strongly typed so it seems not easy to replicate this exact behavior.

    A "possibility" :

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

    Usage :

            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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?