Reason for KeyNotFoundException in Dictionary initialization

倖福魔咒の 提交于 2019-12-19 17:45:51

问题


The following code

new Dictionary<string, List<int>> {
    ["a"] = {1},
};

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

Why does this happen?


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

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

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

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 }.



来源:https://stackoverflow.com/questions/40397939/reason-for-keynotfoundexception-in-dictionary-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!