2013-06-25 27 views
-3

當我試圖檢查給定XML標記的一個實例是否已經出現或者沒有出現在以前的XML文件中時,我收到了這個錯誤,因此,是否應該得到它在數據表中創建自己的列。爲了使事情短,我創建的字符串,存儲列名的佔位符陣,我要檢查,如果XMLReader的閱讀了相同名稱的標籤:C#未分配的本地變量錯誤 - 嘗試了幾種解決方案

// initializing dummy columns 
string[] columns; 

// check if it is a first time occurance of this tag 
for(int n = 0; n < totalcolumns; n++) 
{ 
    if (reader.Name == columns[n]) 
    { 
      columnposition = n; 
      break; 
    } 
    else if(totalcolumns == columntracker+1) 
    { 
      // just adding it to the record-keeping array of tables 
      columns[n] = reader.Name; 
      column.ColumnName = "reader.Name"; 
      dt.Columns.Add(column); 
      columnposition = n; 
    } 

    columntracker++; 
} 

我要指出的是,for循環中的發生switch語句,它只是簡單地檢查XML節點類型。此外,我嘗試做一個開關,但它不允許有一個可變的情況下,即在案例聲明中使用列[n]。

+1

你或許應該分享錯誤信息,以及你試過 –

+4

'//初始化虛擬columns'的解決方案是不準確的。 – Ryan

+2

當前列未分配。將該行定義爲'string [] columns = null;'會使錯誤消失,但當您嘗試訪問'column [n]'時會遇到異常,因爲您沒有分配數組。 –

回答

2

如果要初始化columnstotalcolumnsstring秒的陣列,它看起來像這樣:

string[] columns = new string[totalcolumns]; 
0

雖然從MiniTech移動的回答解決了未初始化變量的問題,我會用一個列表,而不是字符串數組。代碼變得更簡單使用List.FindIndex而不是遍歷字符串數組。

 List<String> columns = new List<string>(); 
     columnposition = columns.FindIndex (s => string.Equals(s, reader.Name); 
     if (columnposition < 0) 
     { 
      columns.Add (reader.Name); 
      columnposition = columns .Count -1; 
      // .. do the other stuff 
     } 
相關問題