列表数组抛出NullReferenceException

我正在尝试制作一个列表列表。 我这样做:

public static List[] words = new List[30]; public static List[] hints = new List[30]; 

我称之为:

 foreach (string item in vars.directory) { reader2 = new StreamReader(item); while (reader2.Peek() > 0) { string line = reader2.ReadLine(); if (line.StartsWith("#")) { vars.words[counter].Add(line.Substring(1, line.Length - 1)); //here } else if (line.StartsWith("-")) { vars.hints[counter].Add(line.Substring(1, line.Length - 1)); //another here } else if (line == "@end") { counter++; } } } 

我只想补充一点,vars是我保存公共变量的地方,当循环开始时,计数器确实为0。

编辑在我的仓促中,我忘了添加问题……哎呀……

这是:当我调用add函数(或任何其他函数)时,它返回一个空引用exception。 我怎样才能解决这个问题?

我假设你在尝试调用.Add你的数组元素时崩溃了。 您需要使用有效对象初始化数组。

 for( Int32 i = 0; i < vars.words.Length; ++i ) vars.words[i] = new List(); for( Int32 i = 0; i < vars.hints.Length; ++i ) vars.hints[i] = new List(); 

为什么不只是创建一个List> ,但是你可以创建一个列表数组

使用已建议的列表列表可以让您逃避问题,并且比您的构造更灵活,更方便。

– > fi如果您的数据大小发生变化,您不必更改列表大小,而是更改数组

这是一个初始化大小为30的列表数组的单行程序:

  static List[] lists = (from i in Enumerable.Range(0, 30) select new List()).ToArray(); 

问题是数组值初始化为默认值,引用类型的默认值为null

default(List)返回null

因此,您需要在可以访问它们之前重新初始化数组中的对象,否则您将获得NullReferenceException

预先初始化arrays中所有对象的一种方法是使用此Linq语句:

 const int sizeOfLists = 5; List[] lists = Enumerable.Range(0, sizeOfLists) .Select(i => new List()) .ToArray(); 

另一个选项是通过使用外部List,仅在需要时初始化和添加子列表:

 var lists = new List>(); // ... var aSubList = new List(); lists.Add(aSubList); 

如果您事先不知道外部列表集的大小,并且仍可通过索引访问,则此function特别有用。

(这是之前的评论,但我做了一个答案,因为许多其他答案都被解决了,并没有描述问题)

您可以在使用它们之前初始化列表:

 foreach (string item in vars.directory) { reader2 = new StreamReader(item); while (reader2.Peek() > 0) { string line = reader2.ReadLine(); // new code if (vars.words[counter] == null) vars.words[counter] = new List(); if (vars.hints[counter] == null) vars.hints[counter] = new List(); if (line.StartsWith("#")) { vars.words[counter].Add(line.Substring(1, line.Length - 1)); //here } else if (line.StartsWith("-")) { vars.hints[counter].Add(line.Substring(1, line.Length - 1)); //another here } else if (line == "@end") { counter++; } } }