字典初始化中KeyNotFoundException的原因

编程入门 行业动态 更新时间:2024-10-18 12:28:07
本文介绍了字典初始化中KeyNotFoundException的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码

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的原因

本文发布于:2023-11-06 14:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   字典   原因   KeyNotFoundException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!