列表的数组抛出的NullReferenceException [英] Array of Lists throws NullReferenceException
问题描述
我试图使列表的一维数组。我做这样的:
I am trying to make a 1d array of lists. I make it like this:
public static List<string>[] words = new List<string>[30];
public static List<string>[] hints = new List<string>[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++;
}
}
}
我只是想补充一点,瓦尔就是我把我的公共变量和计数器的确是在0时循环开始。
I just wanted to add that vars is where I keep my public variables and that counter is indeed at 0 when the loop starts.
修改
在我匆忙我忘了补充问题......哎呀......
EDIT In my haste I forgot to add the question... oops...
这就是:当我调用add函数(或任何与此有关的另一个功能),它返回一个空引用异常。我该如何解决这个问题?
Here it is: When I call the add function (or any another function for that matter) it returns a null reference exception. How can I fix this?
推荐答案
我假设你试图调用。新增
您的数组元素时崩溃。您需要使用有效对象来初始化数组。
I assume you're crashing when attempting to call .Add
on your array element. You need to initialize your arrays with valid objects.
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>();
这篇关于列表的数组抛出的NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!