C#模拟未知键号的关联数组(如PHP) [英] C# mimic associative array of unknown key-number (like in PHP)
本文介绍了C#模拟未知键号的关联数组(如PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能创造某物.像在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";
长度也必须是动态,我没有会有多少键:
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"];
或与此类似的方式.
到目前为止我尝试过的事情:
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";
但是问题从这里开始(仅适用于2个键):
But the problem starts here (only works with 2 keys):
player["custom"]["Face"] = new Hashtable();
player["Custom"]["Face"]["Main"] = "FM1";
推荐答案
C#是强类型的,因此复制这种确切行为似乎并不容易.
C# is strongly typed so it seems not easy to replicate this exact behavior.
可能性":
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
这篇关于C#模拟未知键号的关联数组(如PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文