C#中的字典数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9301225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array of dictionaries in C#
提问by hradecek
I would like to use something like this:
我想使用这样的东西:
Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
But, when I do:
但是,当我这样做时:
matrix[0].Add(0, "first str");
It throws " 'TargetInvocationException '...Exception has been thrown by the target of an invocation."
它抛出“'TargetInvocationException'...调用的目标已抛出异常。”
What is the problem? Am I using that array of dictionaries correctly?
问题是什么?我是否正确使用了该字典数组?
采纳答案by Andrew Hare
Try this:
尝试这个:
Dictionary<int, string>[] matrix = new Dictionary<int, string>[]
{
new Dictionary<int, string>(),
new Dictionary<int, string>()
};
You need to instantiate the dictionaries inside the array before you can use them.
您需要先实例化数组中的字典,然后才能使用它们。
回答by Erik Dietrich
You've initialized the array, but not the dictionary. You need to initialize matrix[0] (though that should cause a null reference exception).
您已初始化数组,但未初始化字典。您需要初始化 matrix[0] (尽管这会导致空引用异常)。
回答by ken
Did you set the array objects to instances of Dictionary?
您是否将数组对象设置为 Dictionary 的实例?
Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
matrix[0] = new Dictionary<int, string>();
matrix[1] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");
回答by Anderson Pimentel
You forgot to initialize the Dictionary. Just put the line below beforeadding the item:
您忘记初始化字典。在添加项目之前,只需在下面添加一行:
matrix[0] = new Dictionary<int, string>();
回答by Thorkil Holm-Jacobsen
Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
Doing this allocates the array 'matrix', but the the dictionaries supposed to be contained in that array are never instantiated. You have to create a Dictionary object in all cells in the array by using the new keyword.
这样做会分配数组“矩阵”,但从未实例化应该包含在该数组中的字典。您必须使用 new 关键字在数组中的所有单元格中创建一个 Dictionary 对象。
matrix[0] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");

