下面的代码演示如果创建和初始化数组,C#中如何将数组元素从一个复制到另外一个
附件中包含了源代码和生成的可执行文件,您可以直接运行测试
using System; public class ArraySample { public static void Main() { // 创建和初始化数组 int[] intArr = new int[5] {1,2,3,4,5}; Object[] objArr = new Object[5] {10,20,30,40,50}; foreach (int i in intArr) { Console.Write(i); Console.Write(","); } Console.WriteLine(); foreach (Object i in objArr ) { Console.Write (i); Console.Write (","); } Console.WriteLine(); // 复制 intArr的前三个元素到 objArr Array.Copy(intArr, objArr,3); Console.WriteLine("After coping" ); foreach (int i in intArr) { Console.Write(i); Console.Write(" , "); } Console.WriteLine( ); foreach (Object i in objArr) { Console.Write(i); Console.Write(" ,"); } Console.WriteLine( ); } }
代码运行输出结果如下
1,2,3,4,5, 10,20,30,40,50, After coping 1 , 2 , 3 , 4 , 5 , 1 ,2 ,3 ,40 ,50 ,
附件:源代码下载