2011-11-19 74 views
0

我正在參加C#編程的基礎課程,這是我們任務的一部分。 編程非常新穎,所以我覺得比這有點失落。從ArrayList中檢索對象 - 強制類型轉換?

的分配是從一個文件到這一點,我希望有與下面的代碼完成添加ArrayList並插入字符串:

  • Read()在另一個類(FileReader)的方法,其讀取來自"info.txt"的文件並返回ArrayList

  • ArrayList項目應該存儲對象項目,雖然我不太清楚爲什麼我需要兩個數組?

我的問題是:當你檢索該數組中的「項目」,他們必須被轉換爲一個類型,string,(如果我理解正確,否則會被返回objects?) 。我怎麼做?

您可以投下整個ArrayList

public PriceFlux() //Constructor 
{ 
    ArrayList items;   
    items = new ArrayList(); 
    FileReader infoFile = new FileReader("info.txt"); 
    items = infoFile.Read(); 
} 

info.txt的文件看起來大致是這樣的:

ģ Kellogsķfrukostflingor & SVERIGE & 29.50 & 2005年5月11日& 29/10/2005 & 29/10/2006

這裏是FileReader Read()方法:

public ArrayList Read() 
{ 
    ArrayList fileContent = new ArrayList(); 
    try 
    {        
     while (line != null) 
     { 
      fileContent.Add (line); 
      line = reader.ReadLine(); 
     } 
     reader.Close(); 
    } 
    catch 
    { 
     Console.WriteLine ("Couldn´t read from file."); 
    } 
    return fileContent; 
} 

非常感謝有關如何解決這個問題的建議。

回答

0

您在使用它之前自行投射每個元素。

1

您可以訪問ArrayList單一元素做一個演員,例如...

string s = myArrayList[100] as string; 
myArrayList.Remove("hello"); 
myArrayList[100] = "ciao"; // you don't need a cast here. 

您也可以通過不進行強制轉換的所有元素重複...

foreach (string s in myArrayList) 
    Console.WriteLine(s); 

你可以還使用CopyTo方法複製的所有項目在一個字符串數組...

string[] strings = new string[myArrayList.Count]; 
myArrayList.CopyTo(strings); 

呦你可以用ArrayList中的所有項目創建另一個List<string>。 由於ArrayList implements IEnumerable您可以撥打List<string>的構造函數。

List<string> mylist = new List<string>(myArrayList); 

但這沒有多大意義......爲什麼你不直接使用List<string>? 直接使用List<string>對我來說似乎更有用,而且速度更快。 ArrayList仍然主要用於兼容目的,因爲泛型是在該語言的第2版中引入的。

我只注意到有可能在你的代碼中的錯誤:

while (line != null) 
    { 
     fileContent.Add (line); 
     line = reader.ReadLine(); 
    } 

應改用

for (;;) 
    { 
     string line = reader.ReadLine(); 
     if (line == null) 
      break; 
     fileContent.Add(line); 
    } 
+1

當然,但也許這個想法是教他們如何在C#/ .NET中利用Object類來處理這些東西。畢竟是家庭作業。 – stefan

+0

在賦值中我們必須使用ArrayList,但我確實已經讀過,儘管使用List 可能更好... Thankyou的建議! – user1055231

5

您可以使用LINQ來做到這一點很容易:

這將投所有項目到string並返回IEnumerable<string>。它會失敗,如果任何項目不能轉換爲string

items.Cast<string>(); 

這將施放的所有項目,可以爲string並跳過任何不能:

items.OfType<string>(); 
+0

感謝您的建議! – user1055231