如何将项目添加到List<>的成员阵列?

时间:2013-10-11 11:01:21

标签: c# arrays list

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

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

但是有一个错误如下:

  

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

这个错误意味着什么,我该如何解决?

5 个答案:

答案 0 :(得分:7)

您已初始化数组,但所有元素都是null。如果您想在给定索引处使用List<String>对其进行初始化,则无法使用Add这是List<T>的方法。

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

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

另请注意,索引从0开始,而不是1。

这是 demonstration

答案 1 :(得分:1)

我认为你混合了List<T>数组

来自MSDN

  

List<T>类是ArrayList类的通用等价物。它   使用大小为的数组实现IList<T>通用接口   根据需要动态增加。

所以,你很容易写,

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

答案 2 :(得分:1)

问题是,在初始化数组时,它是使用项的默认值创建的。对于大多数值类型(int,float,vs ...),默认值将为0.对于引用类型(strings和nullable以及List和许多其他),默认值将为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");

答案 3 :(得分: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");
}

答案 4 :(得分:-1)

宣告:

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

添加:

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

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

相关问题