C# 按索引设置对象列表时获取索引超出范围错误?

C# 按索引设置对象列表时获取索引超出范围错误?,c#,C#,我在更复杂的模型中遇到了这个错误,但这是List对象的行为: List<int> numbers= new List<int>(); numbers[0] = 12; //The error occurs here Console.WriteLine(numbers[0]); 列表编号=新列表(); 数字[0]=12//错误发生在这里 Console.WriteLine(数字[0]); 错误是: 索引超出范围。必须为非负数且小于 收藏 编辑 我知道Add()和Inse

我在更复杂的模型中遇到了这个错误,但这是
List
对象的行为:

List<int> numbers= new List<int>();
numbers[0] = 12; //The error occurs here
Console.WriteLine(numbers[0]);
列表编号=新列表();
数字[0]=12//错误发生在这里
Console.WriteLine(数字[0]);
错误是:

索引超出范围。必须为非负数且小于 收藏

编辑


我知道
Add()
Insert()
,但我想知道为什么会发生这种奇怪的错误。

您需要调用
列表上的
Add
方法,如下所示:

numbers.Add(12)
如果需要使用索引访问,则需要填充列表,然后可以使用
numbers[0]
检索第一个元素

要初始化列表,请执行以下操作:

List<int> numbers = new List<int>
{
    12,
    15,
    18
};
列表编号=新列表
{
12,
15,
18
};

现在,
numbers[1]
将返回15。

您需要调用
列表上的
Add
方法,如下所示:

numbers.Add(12)
如果需要使用索引访问,则需要填充列表,然后可以使用
numbers[0]
检索第一个元素

要初始化列表,请执行以下操作:

List<int> numbers = new List<int>
{
    12,
    15,
    18
};
列表编号=新列表
{
12,
15,
18
};

现在,
numbers[1]
将返回15。

您正试图访问一个不存在的索引(0),因为您正在初始化一个空的
列表。您应该调用
Add()
方法

List<int> numbers= new List<int>();
numbers.Add(12);
Console.WriteLine(numbers[0]);
列表编号=新列表();
增加(12);
Console.WriteLine(数字[0]);

您试图访问一个不存在的索引(0),因为您正在初始化一个空的
列表。您应该调用
Add()
方法

List<int> numbers= new List<int>();
numbers.Add(12);
Console.WriteLine(numbers[0]);
列表编号=新列表();
增加(12);
Console.WriteLine(数字[0]);
创建新的列表对象时,其中没有任何值,因此没有索引

这就是为什么在尝试访问列表中的第0项时会出现错误(如果您了解Java,则类似于IndexOutOfBoundsException)

使用列表上的Add方法将新项目放入其中,而不是尝试通过索引进行设置

numbers.Add(12)
此方法将给定值附加到列表的末尾,并为其创建适当的索引。

创建新列表对象时,该对象中没有任何值,因此没有索引

这就是为什么在尝试访问列表中的第0项时会出现错误(如果您了解Java,则类似于IndexOutOfBoundsException)

使用列表上的Add方法将新项目放入其中,而不是尝试通过索引进行设置

numbers.Add(12)

此方法将给定值附加到列表的末尾,并为其创建适当的索引。

(在由Sahuagin链接的问题中,查找
list[0]=42;//异常
)(在由Sahuagin链接的问题中,查找
list[0]=42;//异常