ในการแปลง ArrayList เป็น Array ให้ใช้วิธี ToArray() ใน C#
ขั้นแรก ตั้งค่า ArrayList -
ArrayList arrList = new ArrayList();
arrList.Add("one");
arrList.Add("two");
arrList.Add("three"); ตอนนี้ ในการแปลง ให้ใช้เมธอด ToArray() -
arrList.ToArray(typeof(string)) as string[];
ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
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);
}
}
} ผลลัพธ์
one two three