2016-03-10 35 views
0

我目前正在研究一個項目,涉及到一個文本文件中包含的信息,並將值存儲到一個數組中,用於確定某本書是否應基於其ID進行「拆分」。爲什麼我的數組顯示爲從未分配給?

我已經宣佈正在執行的方法完成這個任務,並使用StreamReader.

這裏從文本文件中指定的值類string陣列是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 
using System.Data.Odbc; 
using System.Data.OleDb; 
using System.IO; 

namespace ElectionsPollBooks 
{  
    class dbElections 
    {  
     //arrays, ints, for pollbook splits 
     string[] as_splitNumbers; 
     int i_splitCount; 

     public void Process() 
     { 
      //opens conenction 
      OpenConn(); 
      //Gets the precinct info for later parsing 
      GetDistrictInfo(); 
      //populate splits array 
      PopulateSplits(); 
      //the hard work 
      SeperateDataSet(); 
      CloseConn(); 
     } 

     //...other methods in here, not related 
     private void PopulateSplits() 
     { 
      //sets the count 
      i_splitCount = 0; 

      //reads the split file 
      StreamReader sr_splits = new StreamReader(@"a\file\path\here\.txt"); 
      //begin populating the array 
      while (sr_splits.ReadLine() != null) 
      { 
       //split ID 
       as_splitNumbers[i_splitCount] = sr_splits.ReadLine(); 
       i_splitCount = i_splitCount + 1; 
      } 
      sr_splits.Close(); 
      sr_splits.Dispose(); 
     } 
    } 
} 

視覺工作室告訴我在這行:

string[] as_splitNumbers; 

即:

"as_splitNumbers is never assigned to and will always return a null value." 

當我也運行該程序時,它會在while循環中拋出NullReferenceException

我的問題是,當我將StreamReader值分配給as_splitNumbers數組時,我做錯了什麼?我在邏輯中錯過了什麼?

謝謝。

+3

你需要首先聲明在陣列上的長度。 – ragerory

+1

string [] as_splitNumbers =新字符串[SIZE]; – LibertyLocked

+2

您的數組永遠不會聲明長度 - 您最好使用'List '並使用'Add()'方法。 –

回答

2

你沒有初始化你的數組的大小。

,如果你不知道尺寸,你可以做的是使用List<int>.

變化

string[] as_splitNumbers 

List<string> as_SplitNumbers = new List<string>(); 

和你的方法:

private void PopulateSplits() 
    { 
     //sets the count 
     i_splitCount = 0; 

     //reads the split file 
     using(StreamReader sr_splits = new StreamReader(@"a\file\path\here\.txt")) 
     { 
      //begin populating the array 
      while (sr_splits.ReadLine() != null) 
      { 
       //split ID 
       string split = sr_splits.ReadLine(); 
       as_splitNumbers.Add(split); 
       i_splitCount = i_splitCount + 1; 
      } 
     } 
    } 

如果wh在您將它發送到(SeperateDataSet();?)需要一個數組時,您可以稍後使用_asSplitNumbers.ToArray()進行投射。 List<T>只允許您在不知道尺寸的情況下添加。

2

嘗試使用List(System.Enumerable)。因爲在閱讀之前,你不知道數組的大小。

在變量的聲明就會手段:

List<string> as_splitNumbers = new List<string>(); 

在循環中,您可以簡單地寫

as_splitNumbers.Add(sr_splits.ReadLine()) 

,也將努力!

1

您的as_splitNumbers數組從未分配。您需要首先使用大小初始化陣列。

string[] as_splitNumbers = new string[SIZE]; 

但是,似乎你應該只是在你的情況下使用一個列表。

List<string> as_splitNumbers = new List<string>(); 

然後

//split ID 
as_splitNumbers.Add(sr_splits.ReadLine()); 
相關問題