c# 面对 System.NullReferenceException
c# facing System.NullReferenceException
我试图从文本中读取一个整数列表到锯齿状数组中(因为它的每一行包含不同数量的元素,由 space 分隔)但是我在这段代码中遇到 System.NullReferenceException :
integers [counter] [n] = int.Parse (split[n]);
完整代码:
int[][] integers = new int[200][];
int[][] tmp = new int[1][];
int n = 0;
int counter = 0;
string[] file = File.ReadAllLines(@"C:.txt");
foreach (string line in file) {
string [] split = line.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split) {
if (s.Trim () != " ") {
integers [counter] [n] = int.Parse (split[n]);
n++;
}
}
counter++;
}
您有一个或多个数组,但所有这些数组都是空的。您需要在使用索引器之前初始化数组:
integers[counter] = new int[split.Length];
int index = 0;
foreach (string s in split)
{
integers[counter][index] = int.Parse(s);
index++;
}
此外,条件是 redundant.Since 您在 space 上拆分,split
数组将不包含任何 space。
我试图从文本中读取一个整数列表到锯齿状数组中(因为它的每一行包含不同数量的元素,由 space 分隔)但是我在这段代码中遇到 System.NullReferenceException :
integers [counter] [n] = int.Parse (split[n]);
完整代码:
int[][] integers = new int[200][];
int[][] tmp = new int[1][];
int n = 0;
int counter = 0;
string[] file = File.ReadAllLines(@"C:.txt");
foreach (string line in file) {
string [] split = line.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split) {
if (s.Trim () != " ") {
integers [counter] [n] = int.Parse (split[n]);
n++;
}
}
counter++;
}
您有一个或多个数组,但所有这些数组都是空的。您需要在使用索引器之前初始化数组:
integers[counter] = new int[split.Length];
int index = 0;
foreach (string s in split)
{
integers[counter][index] = int.Parse(s);
index++;
}
此外,条件是 redundant.Since 您在 space 上拆分,split
数组将不包含任何 space。