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 ý:
ArrayListlà non-generic, lưuobjectToArray(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