2011-11-19 70 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