列表数组抛出NullReferenceException

Ada*_*one 1 c# arrays list

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

public static List<string>[] words = new List<string>[30];
public static List<string>[] hints = new List<string>[30];
Run Code Online (Sandbox Code Playgroud)

我称之为:

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++;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

编辑 在我的匆忙中,我忘了添加问题......哎呀......

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

Avi*_*ilo 7

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

for( Int32 i = 0; i < vars.words.Length; ++i )
  vars.words[i] = new List<string>();
for( Int32 i = 0; i < vars.hints.Length; ++i )
  vars.hints[i] = new List<string>();
Run Code Online (Sandbox Code Playgroud)


msa*_*het 6

为什么不做一个List<List<string>>,但是你可以制作一系列列表