2016-03-04 28 views
0

我對C#比較陌生,但我遇到了我認爲是範圍問題的問題,但一直無法通過web搜索找到類似的問題/解決方案。在streamreader中使用'block'創建的c#數組的作用域

我想讀取一個csv文件的內容到一個多維的int數組。該文件包含「控制」值,這些值將用於程序後面出現的步驟中的比較/決策。

到目前爲止,我所能達到的最接近的方法是使用streamReader讀取文件,將每行分成不同的值,並將字符串值轉換爲int32。所有這些發生在'using'塊內的'while'塊內。在進入'使用'模塊之前,數組被定義/初始化。

我已經驗證通過在while語句中插入斷點並檢查數組內容,正確的int值被分配給適當的數組元素。但是,一旦退出'while'塊,數組內容無效;不是空的,只是無效。所有初始化爲0或填充0的數組元素仍然包含0.但是,之前填充非零數字的元素現在最多包含4位數字。在我看來,修剪/截斷在我看來並沒有什麼意義,因爲後「時間」值是完全不同的值。

例如,目標[1,0,1,9]被填充41513,該值在'while'內正確顯示爲整數41513,但只要我退出'while'塊,target [1, 0,1,9]始終包含3718.

我試過了幾種方法,我在網上找到了,但我上面描述的那個方法在同一個問題中得到了結果。

示例代碼如下。

static void Main(string[] args) 
    { 
     int[,,,] target = new int[60, 3, 6, 86]; 
     int[,,,] accum = new int[60, 3, 6, 86]; 
     char[] delims = new char[] { ',' }; 
     int g = new int(); 
     int a = new int(); 
     int b = new int(); 
     int c = new int(); 
     int d = new int(); 
     string e = null; 
     string f = null; 

     using (StreamReader myRdr1 = new StreamReader("f:\\targetData.csv")) 
     { 
      string line; 
      myRdr1.ReadLine();  // skip over the column headers 
      while ((line = myRdr1.ReadLine()) != null) 
      { 
       string[] words = line.Split(delims); 
       a = System.Convert.ToInt32(words[2]); 
       b = System.Convert.ToInt32(words[3]); 
       c = System.Convert.ToInt32(words[5]); 
       d = System.Convert.ToInt32(words[6]); 
       e = words[10]; 
       f = words[11]; 
       target[a, b, c, d] = System.Convert.ToInt32(words[9]); 

      } 
     } 

     for (int i = 1; i < 60; i++) 
     { 
      Console.WriteLine(g.ToString()); 
      Console.WriteLine(); 
      Console.WriteLine(target[1, 0, 1, 9]); 
      Console.ReadLine(); 
      for (int j = 0; j < 3; j++) 
      { 
       for (int k = 0; k < 6; k++) 
       { 
        for (int l = 0; l < 86; l++) 
        { 
         Console.WriteLine("a " + i.ToString() + 
              ", b " + j.ToString() + 
              ", c " + k.ToString() + 
              ", d " + l.ToString() + 
              "=  " + target[i, j, k, l]); 
         Console.ReadLine(); 
        } 
       } 
      } 

     } 

    } 
+0

確定索引是否正確?我的猜測是你只是在一些迭代後跳過調試while循環,所以你看不到的下一次迭代將會因爲索引不正確而再次改變之前的初始化值。確保調試整個迭代。如果文件很大,用較小的文件測試你的代碼。 –

+0

你確定,你還沒有用不同的值重新填充數組? – Rahul

+2

你能提供你的輸入文件的樣本嗎? – Steve

回答

0

對我來說,這個問題看起來像在下面的線,你與words[9]初始化數組值的所有索引,因此以前的值可能得到新的值覆蓋。

target[a, b, c, d] = System.Convert.ToInt32(words[9]); 
+0

是的,如果任何兩行在單詞上有相同的值2,3,5和6,那麼第二行的單詞9將覆蓋從第一行解析的值。 – hypehuman