c#模拟未知键数的关联数组(类似于PHP)

本文关键字:数组 类似于 PHP 关联 模拟 未知 | 更新日期: 2023-09-27 18:14:57

是否有可能创建像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";

c#模拟未知键数的关联数组(类似于PHP)

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