简体   繁体   English

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

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

I'm taking a basic course in C# programming, and this is a part of our assignment. 我正在学习C#编程的基础课程,这是我们作业的一部分。 Very new to programming so I feel more than a bit lost with this. 编程非常陌生,因此我对此感到不知所措。

The assignment is to add an ArrayList and insert strings from a file to this, which I hopefully have done with the code below: 任务是添加一个ArrayList并将文件中的字符串插入此文件,我希望可以使用以下代码完成此操作:

  • Read () is a method in another class ( FileReader ) that reads the files from "info.txt" and returns an ArrayList . Read ()是另一个类( FileReader )中的方法,该方法从"info.txt"读取文件并返回ArrayList

  • The ArrayList items are supposed to store the object items, although I'm not quite sure why I need two arrays? 尽管我不太确定为什么需要两个数组,但是ArrayList项应该存储对象项。

The problem I have is: when you retrieve the "items" from the array, they have to be cast to a type, string , (if I understand it correctly, otherwise they are returned as objects ?). 我的问题是:当您从数组中检索“项目”时,必须将它们转换为string类型(如果我正确理解的话,否则它们将作为objects返回?)。 How do I do that? 我怎么做?

Can you cast the entire ArrayList ? 您可以转换整个ArrayList吗?

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

The files from the info.txt looks approximately like this: info.txt的文件大致如下所示:

G&34&Kellogs K frukostflingor&Sverige&29.50&5/11/2005&29/10/2005&29/10/2006 G&34&Kellogs K frukostflingor&Sverige&29.50&5/11/2005&29/10/2005&29/10/2006

Here is the FileReader Read() method: 这是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;
}

Very grateful for suggestions on how to solve this. 非常感谢有关如何解决此问题的建议。

You can use linq to do this easily: 您可以使用linq轻松做到这一点:

This will cast all items to string and return an IEnumerable<string> . 这会将所有项目转换为string并返回IEnumerable<string> It will fail if any items can't be cast to a string : 如果任何项目都不能转换为string ,它将失败:

items.Cast<string>();

This will cast all items that can be to a string and skip over any that can't: 这会将所有可能为string项目强制转换为string并跳过所有不能的项目:

items.OfType<string>();

You can access single elements in the ArrayList doing a cast, for example... 您可以执行转换来访问ArrayList单个元素,例如...

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

You can also iterate through all elements without a cast... 您还可以在没有强制转换的情况下遍历所有元素。

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

You can also use CopyTo method to copy all items in a string array... 您还可以使用CopyTo方法复制字符串数组中的所有项目。

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

You can create another List<string> with all items in the ArrayList . 您可以使用ArrayList所有项目创建另一个List<string> Since ArrayList implements IEnumerable you can call the List<string> constructor. 由于ArrayList实现IEnumerable ,因此可以调用List<string>构造函数。

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

But this doesn't makes much sense... why you don't just use List<string> directly? 但这没有多大意义...为什么不直接使用List<string> Using directly a List<string> seems more useful to me, and is faster. 直接使用List<string>对我来说似乎更有用,而且速度更快。 ArrayList still exists mostly for compatibility purposes since generics were introduced in version 2 of the language. ArrayList仍然主要出于兼容性目的而存在,因为泛型是在该语言的版本2中引入的。

I just noticed that there may be an error in your code: 我只是注意到您的代码中可能存在错误:

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

Should be instead 应该代替

    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