如何将项目添加到 List<> 数组的成员

本文关键字:数组 成员 List 项目 添加 | 更新日期: 2023-09-27 18:34:50

如何将项目添加到数组List<>成员?
请看下面的例子:

List<string>[] array_of_lists = new List<string>[10];
array_of_lists[1].Add("some text here");

但是有以下错误:

对象引用未设置为对象的实例。

此错误是什么意思,我该如何解决?

如何将项目添加到 List<> 数组的成员

您已经初始化了数组,但所有元素都已null。如果要在给定索引处使用List<String>初始化它,则不能使用Add这是一种List<T>的方法。

通过这种方式,您可以在第二个元素处启动数组:

array_of_lists[1] = new List<string>{"some text here"};

另请注意,索引以 0 开头,而不是 1。

这是一个演示

经过如此多的编辑,更改和注释答案,我想为您提供一个完整的解决方案:

List<string>[] array_of_lists = new List<string>[10];
for (int i = 0; i < array_of_lists.Length; i++) {
    array_of_lists[i] = new List<string>();
    array_of_lists[i].Add("some text here");
    array_of_lists[i].Add("some other text here");
    array_of_lists[i].Add("and so on");
}

问题是,当您初始化数组时,它是使用项的默认值创建的。对于大多数值类型(int、float、vs...(,默认值将为 0。对于引用类型(字符串和可为空以及列表和许多其他类型(,默认值将为 NULL。

所以你的代码应该是这样的

List<string>[] list_lines_link_scanner_ar = new List<string>[int.Parse(txt_ParaCount_In_LinkScanner.Text)];
// this is the line -->
list_lines_link_scanner_ar[1] = new new List<string>();
//  <----
list_lines_link_scanner_ar[1].Add("some text here");

我想你混合了List<T>数组

MSDN

List<T>类是 ArrayList 类的泛型等效项。它 使用大小为IList<T> 根据需要动态增加。

所以,你很容易写,

List<string> array_of_lists = new List<string>();
array_of_lists.Add("some text here");

声明:

List<List<string>> listOfList = new List<List<string>>();

加:

listOfList.Add(new List<string> { "s1", "s2", "s3" });

除非你真的需要一个数组。