Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển ArrayList sang Array trong C#

Dùng ToArray() method:

ArrayList arrList = new ArrayList();
arrList.Add("one");
arrList.Add("two");
arrList.Add("three");

string[] arr = arrList.ToArray(typeof(string)) as string[];

Ví dụ hoàn chỉnh

using System;
using System.Collections;

public class Program
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add("one");
        arrList.Add("two");
        arrList.Add("three");
        
        string[] arr = arrList.ToArray(typeof(string)) as string[];
        
        foreach (string res in arr)
            Console.WriteLine(res);
    }
}

Kết quả

one
two
three

Lưu ý:

  • ArrayList là non-generic, lưu object
  • ToArray(typeof(T)) cần cast
  • Khuyên dùng List<T> thay ArrayList (type-safe, hiệu năng tốt hơn)
  • Với List<T>: list.ToArray() trả về T[] trực tiếp