Skip to main content
 首页 » 编程设计

c#之解析文本文件时出错

2024年02月23日17shangdawei

伙计们,我的代码有一个错误,我不明白为什么,这是我的代码:

private void Parsing_String(string filename) 
    { 
        int outValue; 
        int[][] number = new int[26][]; 
        List<Row> list = new List<Row>();  
 
        //StreamReader freader = File.OpenText(filename); 
 
        var parsed = File.ReadLines(filename) 
            .Select(line => line.Split(' ') 
                .Where(IsInteger) 
                .Select(s => int.Parse(s)) 
                .ToArray()) 
            .ToArray(); 
 
        foreach (String str in File.ReadLines(filename)) 
        { 
            String[] strCols = str.Split(' '); 
 
            /*for (int i = 0; i < 26; i++) 
            { 
                number[i] = new int[strCols.Length]; 
                for (int j = 0; j < strCols.Length; j++) 
                { 
                    number[i][j] = int.TryParse(strCols[j].Substring(2), out outValue) ? outValue : 0; 
                    listBox2.Items.Add(number[i][j]); 
                } 
            }*/ 
 
 
            list.Add(new Row() 
            { 
                Column1 = int.TryParse(strCols[0].Substring(2), out outValue) ? outValue : 0, 
                Column2 = int.TryParse(strCols[1].Substring(2), out outValue) ? outValue : 0, 
                Column3 = int.TryParse(strCols[2].Substring(2), out outValue) ? outValue : 0, 
                Column4 = int.TryParse(strCols[3].Substring(2), out outValue) ? outValue : 0, 
                Column5 = int.TryParse(strCols[4].Substring(2), out outValue) ? outValue : 0, 
                Column6 = int.TryParse(strCols[5].Substring(2), out outValue) ? outValue : 0, 
            }); 
 
        } 
 
        dg.ItemsSource = list; 
 
 
        label3.Content = number[1][0]; 
        label4.Content = number[0][1]; 
        int kali = number[0][0] * number[0][1]; 
        label2.Content = kali; 
    } 
 
    static bool IsInteger(string possibleInt) 
    { 
        int k; 
        return int.TryParse(possibleInt, out k) ? k : 0;         
    } 
 
 
    public class Row 
    { 
        public int Column1 { get; set; } 
        public int Column2 { get; set; } 
        public int Column3 { get; set; } 
        public int Column4 { get; set; } 
        public int Column5 { get; set; } 
        public int Column6 { get; set; } 
    } 
 
    #endregion 
 
 
} 

} //这里是文本文件示例 10192 20351 30473 40499 50449 60234 10192 20207 30206 40203 50205 60226 10192 20252 30312 40376 50334 60252 10192 20271 30332 40405 50209 60234

谁能告诉我我做错了什么?

我想做的是,我有一个包含数字的文本文件,我想解析它,并将每个数字放入一个数组中,以便我可以轻松访问它。我的代码是否足够有效?

非常感谢您的建议。

请您参考如下方法:

你的主要错误似乎是这样的:

int[][] number = new int[26][]; 

这只会实例化一个数组的数组,而不是嵌套数组本身,所以当你写的时候

number[i][j] = ... 

number[i] 返回 null,在 null 上调用索引器是 NullReferenceException!

编辑:
你应该写的是:

for (int i = 0; i < 26; i++) 
{ 
  number[i] = new int[strCols.Length]; 
  for (int j = 0; j < strCols.Length; j++) 
  { 
      //... 
  } 
}