繁体   English   中英

从ArrayList检索对象-强制转换为类型?

[英]Retrieving objects from ArrayList - cast to type?

我正在学习C#编程的基础课程,这是我们作业的一部分。 编程非常陌生,因此我对此感到不知所措。

任务是添加一个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的文件大致如下所示:

G&34&Kellogs K frukostflingor&Sverige&29.50&5/11/2005&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;
}

非常感谢有关如何解决此问题的建议。

您可以使用linq轻松做到这一点:

这会将所有项目转换为string并返回IEnumerable<string> 如果任何项目都不能转换为string ,它将失败:

items.Cast<string>();

这会将所有可能为string项目强制转换为string并跳过所有不能的项目:

items.OfType<string>();

您可以执行转换来访问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实现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);
    }

在使用每个元素之前,您必须对其进行单独转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM