包含字典

时间:2015-11-21 16:53:09

标签: c# c#-4.0

我尝试用字典制作二维列表 我想在每个小时,剩下的时间,正确的时间制作它。

凌晨1点,ActionEnum.Left = 10,ActionEnum.Right = 20
凌晨2点,ActionEnum.Left = 40,ActionEnum.Right = 50
凌晨3点,ActionEnum.Left = 60,ActionEnum.Right = 70
凌晨4点,ActionEnum.Left = 30,ActionEnum.Right = 40

...

Dictionary<ActionEnum, int> indexer1 = new Dictionary<ActionEnum, int>();
ActionEnum[] values = (ActionEnum[])Enum.GetValues(typeof(ActionEnum));
for (int i = 0; i < values.Length; i++)
{
    indexer1.Add(values[i], i);
}

Dictionary<int, Dictionary<ActionEnum, int>> indexer2 = new Dictionary<int, Dictionary<ActionEnum, int>>(); 
for (int i = 0; i < 24; i++)
{
    indexer2.Add(i, indexer1);
}


indexer2[0][ActionEnum.Left] = 10; indexer2[0][ActionEnum.Right] = 20;
indexer2[1][ActionEnum.Left] = 40; indexer2[1][ActionEnum.Right] = 50;
indexer2[2][ActionEnum.Left] = 60; indexer2[2][ActionEnum.Right] = 70;
indexer2[3][ActionEnum.Left] = 30; indexer2[3][ActionEnum.Right] = 40;

for (int i = 0; i < 24; i++)
{
    for (int j = 0; j < values.Length; j++)
    {
        Console.Write(indexer2[i][(ActionEnum)j] + " ");
    }
    Console.WriteLine();
}

它似乎有效,但是当我指定了值时,dictonary持有最后的值。你能给我一些帮助吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

因为indexer1是通过引用添加到indexer2的。每次要将其添加到另一个字典时,都需要创建新的字典。使用new关键字创建新词典。将你的第二个循环改为此。

for (int i = 0; i < 24; i++)
{
    indexer2.Add(i, new Dictionary<ActionEnum, int>(indexer1));
}