c#数组初始化与数组元素复制
以下例子演示了如何创建与初始化数组,以及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 ,