2015-09-27 27 views
-2

我的代碼是:使用未分配的局部變量數組

string text; 
int i = 1; 
string[] payloadwords; 
StreamReader RD = new StreamReader(openfilepay.FileName); 
while ((text = RD.ReadLine()) != null) 
{ 
    text = payloadwords[i]; 
    i++; 
} 

我得到的錯誤是:

錯誤1只使用未分配的局部變量的 'payloadwords'

有任何解決這個問題的方法?

+1

今天是什麼?這是今天這種類型的第三個問題? – MickyD

+1

你想試試,'payloadwords [i] = text;'? – Abhishek

+1

[Use of unassigned local variable'dictionary'](http://stackoverflow.com/questions/3066792/use-of-unassigned-local-variable-dictionary)可能的重複。這是關於字典,但概念是相同的 – MickyD

回答

0

除了有關分配變量的問題之外。 (string[] payloadwords = new string[length];

因爲在這裏你不能使用數組元素的數量是未知的,所以你必須使用List<string>來代替。

string text; 
List<string> payloadwords = new List<string>(); // notice the assigned instance of list 
StreamReader RD = new StreamReader(openfilepay.FileName); 
while ((text = RD.ReadLine()) != null) 
{ 
    payloadwords.Add(text); 
} 

你不需要計數器(i)這裏。您可以添加一個新的元素以Add方法列出。

1

這是1班輪,請查看System.IO.File方法。

string[] payloadwords = System.IO.File.ReadAllLines(openfilepay.FileName); 
+0

不錯。明顯! –