数组初始化
string[] arrayA = { "Shirdrn", "Hamtty", "Saxery" };
Console.WriteLine("第一种声明数组并初始化的方法");
string[] arrayB;
arrayB = new string[] { "shirdrn", "Hamtty", "Saxery" };
Console.WriteLine("第二种声明数组并初始化的方法");
string[] arrayC = new string[];
arrayC[] = "Shirdrn";
arrayC[] = "Hamtty";
arrayC[] = "Saxery";
Console.WriteLine("第三种声明数组并初始化的方法");
unity中,数组长度可动态指定,即声明数组时,不用指明数组长度,可在inspector中指定数组长度。同时,可利用unity进行数组批量初始化(指定长度为1,赋初值,修改数组长度)
数组遍历
// for循环遍历数组..
int[] Sum = new int[];
Random rd = new Random();
// 先用for循环给数组取随机数.
for (int s = ; s <= Sum.Length - ; s++) // Sum.Length是数组的一个属性,Length代表数组的长度
{
Sum[s] = rd.Next();
}
// foreach遍历数组输出
foreach (int t in Sum)
{
Console.WriteLine(t);
}
删除元素
(1)for循环遍历
for(int i=;i<;i++)
{
demo[i]=;
}
(2)重新分配空间
demo = new int[];
(3)使用Array.Clear
Array.Clear(demo,,);
注:使用方法(3)可指定要清除数组的起始位置及要清除的个数;当重新分配空间的次数较少时,(2)方法性能最佳。方法(3)性能较为稳定
数组合并
(1)使用for循环
int []pins = } ;
int []copy = new int[pins.length];
for(int i ;i!=copy.length;i++)
{
copy[i] = pins[i];
}
(2)CopyTo()
语法:public void CopyTo(Array array,int index)
参数:
array:一维数组,它是从当前数组复制的元素的目标。
index:表示 array 中复制开始处的索引。
实例:
int[] pins = {,,, };
int[] copy = new int[pins.Length];
pins.CopyTo(copy,); //cops:9 3 7 2
int[] pins1 = {,,, };
int[] copy1 = { };
pins.CopyTo(copy1,); //cops1:0 9 3 7 2 0 0 0
(3)Copy()
语法:public static void Copy(Array sourceArray,Array destinationArray,int length)
参数:
sourceArray:包含要复制的数据的 Array。
destinationArray:接收数据的 Array。
length:一个 32 位整数,它表示要复制的元素数目。
举例:
int[] pins = {,,, };
int[] copy = new int[pins.Length];
Array.Copy(pins, copy,);//cops:9 3 0 0
(4)Clone()
语法:public object Clone()
举例:
int []pins = {,,,};
int []copy4 = (int [])pins.Clone();
二维数组
/ 声明一个锯齿型数组,该数组有两个元素
int[][] myArray = new int[][];
// 其中第一个元素是一个含有五个元素的数组
// 初始化myArray[0]
myArray[] = new int[] {,,,,};
// 其中第二个元素是一个含有4个元素的数组
// 初始化myArray[1]
myArray[] = new int[] {, , , };
// 逐一打印出数组的数组中所有的元素
for (int i=; i < myArray.Length; i++)
{
Console.Write("第({0})个数组: ", i);
// 打印一维数组中的元素
for (int j=; j < myArray[i].Length; j++)
{
Console.Write("{0} ", myArray[i][j]);
}
Console.WriteLine();