如何使用multitype创建多维数组?

时间:2015-04-26 09:53:19

标签: c# arrays multidimensional-array

我曾经在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#中做同样的事情?

1 个答案:

答案 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},
        }
    }
};

有关DictionaryDynamic的详细信息,请参阅文档。

修改

正如其他人所建议的那样,您可能最好使用:

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