以下代码
new Dictionary<string, List<int>> { ["a"] = {1}, };抛出运行时 KeyNotFoundException {1}是一个格式良好的数组(即 int [] a = {1,2,3,4} 是有效的代码)。将词典的 TValue 更改为 int [] ,抛出编译时 CS1061 ,但这不会(请注意添加的 new [] 数组分配):
Throws a run-time KeyNotFoundException, albeit that {1} is a perfectly well-formed array (i.e. int[] a = {1,2,3,4} being valid code). Changing the TValue of the Dictionary to int[], throws a compile-time CS1061, but this does not (note the added new[] array-allocation):
new Dictionary<string, IEnumerable<int>> { ["a"] = new[]{1}, };为什么会这样?
推荐答案您的第一段代码使用的是集合初始值设定项,该初始值设定项不使用逻辑分配,而是用于调用在现有集合上添加。换句话说,这是
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. In other words, this:
var x = new Dictionary<string, List<int>> { ["a"] = {1}, };等同于:
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.
推理中的部分错误是:
尽管{1}非常好格式的数组
albeit that {1} is a perfectly well-formed array
不,不是。语法 {1} 在不同的上下文中表示不同的内容。在这种情况下,它是一个集合初始化程序。在语句中:
No, it's not. The syntax {1} means different things in different contexts. In this case, it's a collection initializer. In the statement:
int[] a = { 1, 2, 3, 4 };它是一个数组初始值设定项。该语法 only 仅在数组声明中创建新数组,或者作为数组创建表达式的一部分,例如 new [] {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, e.g. new[] { 1, 2, 3, 4 }.
更多推荐
字典初始化中KeyNotFoundException的原因
发布评论