我曾经在PHP中创建这种数组:
$myarray[0]["my_string_1"] = "Toto";
$myarray[0]["my_string_2"] = "Tata";
$myarray[0]["my_int_1"] = 25;
$myarray[0]["my_int_2"] = 28;
$myarray[1]["my_string_1"] = "Titi";
$myarray[1]["my_string_2"] = "Tutu";
$myarray[1]["my_int_1"] = 12;
$myarray[1]["my_int_2"] = 15;
我的问题是: 是否有可能在C#中做同样的事情?
答案 0 :(得分:1)
不熟悉PHP,但看起来你的数组有一个字符串到string或int的'map'。这可以使用Dictionary和Dynamic在C#中完成:
var myarray = new Dictionary<int, Dictionary<string, dynamic>>()
{
{
0, new Dictionary<string, dynamic>()
{
{"my_string_1", "Toto"},
{"my_string_2", "Tata"},
{"my_int_1", 25},
{"my_int_2", 28},
}
},
{
1, new Dictionary<string, dynamic>()
{
{"my_string_1", "Titi"},
{"my_string_2", "Tutu"},
{"my_int_1", 12},
{"my_int_2", 15},
}
}
};
有关Dictionary和Dynamic的详细信息,请参阅文档。
修改强>
正如其他人所建议的那样,您可能最好使用:
var myarray = new Dictionary<int, Dictionary<string, object>>()
而不是使用以int
为密钥的字典,可以使用实际的数组:
var myarray = new Dictionary<string, object>[2];
myarray[0] = new Dictionary<string, object>
{
{"my_string_1", "Toto"},
{"my_string_2", "Tata"},
{"my_int_1", 25},
{"my_int_2", 28},
};
myarray[1] = new Dictionary<string, object>
{
{"my_string_1", "Titi"},
{"my_string_2", "Tutu"},
{"my_int_1", 12},
{"my_int_2", 15},
};