本实例主要介绍如何使用Array类的Copy方法来复制数组中一系列的元素。Copy方法从指定的源索引开始,复制Array中的一系列元素,将他们粘贴到另一个Array中(从指定的目标索引开始)。长度和索引指定为64位整数。其方法有多种重载形式,本实例所使用的重载形式如下:
Public static void Copy (Array sourceArray,long sourceIndex,Array destinationArray,long destinationIndex,long length )
参数说明
sourceArray:Array,包含要复制的数据。
sourceIndex: 一个64位整数,表示sourceArray中复制开始处索引。
destinationArray: Array,接受数据。
destinationIndex: 一个64位整数,表示destinationArray中存储开始处的索引。
length: 一个64位整数,表示要复制的元素数目。该整数必须介于零和Int32.MaxValue之间(包括零和Int32.MaxValue)。
主要代码如下:
Private void button1_Click(object sender,EventArgs e)
{
Array myIntArray=Array.CreateInstance(typeof(System.Int32),5)
For(int i=myIntArray.GetLowerBound(0);i<=myIntArray.GetUpperBound(0);i++)
myObjArray.SetValue(i+1,i)//给数组赋值
Array myObjArray=Array/CreateInstance(typeof(System.Object),5)//定义一个长度为5一维数组;
For(int i=myObjArray.GetLowerBound(0); i<=myObjArray.GetUpperBound(0));i++)
myObjArray.SetValue(i+26,i);//给数组赋值
string strMyIntArra=”myIntArray数组复制前”;
string strmyObjArray=”myObjArray数组复制前”;
for(int i=0;i<myIntArray.Length;i++)//取出数组中的值
{
StrMyIntArra=+myIntArray.GetValue(i).ToString()+”,”;
}
For(int i=0;i<myObjArray.Length;i++)//取出数组中的值
{
strmyObjArray+=myObjArray.GetValue(i).ToString()+”,”;
}
String strMyIntArrayAfter=”myIntArray数组复制后:”;
String strmyObjArrayAfter=”myObjArray数组复制后:”;
Array.Copy(myIntArray.myIntArray.GetLowerBound(0),myObjArray,myObjArray.GetLowerBound(0),1);
//复制数组中2个元素
Array.Copy(myIntArray.myIntArray.GetUpperBound(0),myObjArray,myIntArray.GetUpperBound(0),-1,2);
//复制数组中3个元素
For(int i=0;i<myIntArray.Length;i++)//取出数组中的值
{
strMyIntArraAfter+=myIntArray.GetValue(i).ToString()+”,”;
}
For(int i=0;i<myObjArray.Length;i++)//取出数组中的值
{
strmyObjArrayAfter+=myObjArray.GetValue(i).ToString()+”,”;
}
MessageBox.Show(strMyIntArra+”/n”+strmyObjArray+”/n”+strMyIntArraAfter+”/n”+strmyObjArrayAfter,”复制数组中的元素”,MessageBoxButtons.OK,
MessageBoxIcon.Information)
}