用索引初始化列表<T>——这是一个错误吗?

问题描述 投票:0回答:1

在 C# 中,你可以像这样初始化

Dictionary<TKey,TValue>

var dictionary = new Dictionary<int, string>()
{
  [0] = "Hello",
  [1] = "World"
};

你也可以像这样初始化

List<T>

var listA = new List<string>()
{
  "Hello",
  "World"
};

上面列出的两个示例编译并运行没有异常。

但是,以下示例可以编译,但会抛出异常:

var listB = new List<string>()
{
  [0] = "Hello",
  [1] = "World"
};
// System.ArgumentOutOfRangeException: Index was out of range.
// Must be non-negative and less than the size of the collection.
// (Parameter 'index') at System.Collections.Generic.List`1.set_Item(Int32 index, T value)

这是一个未完成的功能吗,因为它编译但抛出异常?如果不是的话,这不是编译错误吗?

我正在使用 C# 12 和 ASP.NET 8

c# list initializer index-error outofrangeexception
1个回答
1
投票
var listB = new List<string>()
{
  [0] = "Hello",
  [1] = "World"
};

编译为:

List<string> list = new List<string>();
list[0] = "Hello";
list[1] = "World";

来自文档

前面的示例生成调用 Item[TKey] 来设置值的代码。

当然,异常是有道理的,因为当您初始化列表时,它有零个元素。数组 0 和 1 中的元素不存在。

© www.soinside.com 2019 - 2024. All rights reserved.