[英]Reason for KeyNotFoundException in Dictionary initialization
The following code 以下代码
new Dictionary<string, List<int>> {
["a"] = {1},
};
Throws a run-time KeyNotFoundException
, albeit that {1} is a perfectly well-formed array (ie int[] a = {1,2,3,4}
being valid code). 抛出一个运行时
KeyNotFoundException
,虽然{1}是一个结构完美的数组(即int[] a = {1,2,3,4}
是有效代码)。 Changing the TValue
of the Dictionary
to int[]
, throws a compile-time CS1061
, but this does not (note the added new[]
array-allocation): 将
Dictionary
的TValue
更改为int[]
,抛出编译时CS1061
,但这不会(注意添加的new[]
数组分配):
new Dictionary<string, IEnumerable<int>> {
["a"] = new[]{1},
};
Why does this happen? 为什么会这样?
Your first piece of code is using a collection initializer, which doesn't use logical assignment, but instead is intended to call Add
on an existing collection. 您的第一段代码使用的是集合初始值设定项,它不使用逻辑赋值,而是用于在现有集合上调用
Add
。 In other words, this: 换句话说,这个:
var x = new Dictionary<string, List<int>> {
["a"] = {1},
};
is equivalent to: 相当于:
var tmp = new Dictionary<string, List<int>>();
var list = tmp["a"];
list.Add(1);
var x = tmp;
Hopefully it's obvious from that why the second line of the expansion would throw an exception. 希望很明显,为什么扩展的第二行会引发异常。
Part of your error in reasoning is: 你在推理中的部分错误是:
albeit that {1} is a perfectly well-formed array
虽然{1}是一个结构完美的阵列
No, it's not. 不,这不对。 The syntax
{1}
means different things in different contexts. 语法
{1}
在不同的上下文中表示不同的东西。 In this case, it's a collection initializer. 在这种情况下,它是一个集合初始化程序。 In the statement:
在声明中:
int[] a = { 1, 2, 3, 4 };
it's an array initializer. 它是一个数组初始化器。 That syntax only creates a new array in an array declaration, or as part of an array creation expression, eg
new[] { 1, 2, 3, 4 }
. 该语法仅在数组声明中创建新数组,或者作为数组创建表达式的一部分创建,例如
new[] { 1, 2, 3, 4 }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.