到的ArrayList的元素复制到一个新的数组,代码如下 -
using System; using System.Collections; public class Demo { public static void Main(){ ArrayList list = new ArrayList(10); list.Add("A"); list.Add("B"); list.Add("C"); list.Add("D"); list.Add("E"); list.Add("F"); list.Add("G"); list.Add("H"); list.Add("I"); list.Add("J"); Console.WriteLine("ArrayList elements..."); foreach(string str in list){ Console.WriteLine(str); } Console.WriteLine("Array elements copied from ArrayList..."); object[] ob = list.ToArray(); foreach(string str in ob){ Console.WriteLine(str); } } }
输出结果
这将产生以下输出-
ArrayList elements... A B C D E F G H I J Array elements copied from ArrayList... A B C D E F G H I J
现在让我们来看另一个示例-
using System; using System.Collections; public class Demo { public static void Main(){ ArrayList list = new ArrayList(10); list.Add(100); list.Add(200); list.Add(300); Console.WriteLine("ArrayList elements..."); foreach(int val in list){ Console.WriteLine(val); } Console.WriteLine("Array elements copied from ArrayList..."); object[] ob = list.ToArray(); foreach(int val in ob){ Console.WriteLine(val); } } }
输出结果
这将产生以下输出-
ArrayList elements... 100 200 300 Array elements copied from ArrayList... 100 200 300