數組初始化
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();