Retrieving objects from ArrayList - cast to type?

后端 未结 3 1409
说谎
说谎 2021-01-27 08:36

I\'m taking a basic course in C# programming, and this is a part of our assignment. Very new to programming so I feel more than a bit lost with this.

The assignment is t

3条回答
  •  逝去的感伤
    2021-01-27 09:10

    You can access single elements in the ArrayList doing a cast, for example...

    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...

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

    You can create another List with all items in the ArrayList. Since ArrayList implements IEnumerable you can call the List constructor.

    List mylist = new List(myArrayList);
    

    But this doesn't makes much sense... why you don't just use List directly? Using directly a List seems more useful to me, and is faster. ArrayList still exists mostly for compatibility purposes since generics were introduced in version 2 of the language.

    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);
        }
    

提交回复
热议问题