很久都沒寫筆記了,前段時間由於工作再加上雜七雜八的事情一直沒時間寫,也沒心情寫,這段時間空下來了,有時間了,寫點簡單的吧,此文適合於新手,高手就請繞道。
吐槽完畢,本文開始:
一. 數組的聲明
int[] myArray
二. 數組的初始化
使用new指定數組中的元素和數量來來初始化數組的變數
myArray = new int[4];
在聲明和初始化數組後,變數myArray就引用了4個整型值,它們位於託管堆上,在指定了數組大小後,如果不複製數組中的所有元素,就不能重新設定數組的大小。
除了在兩個語句中聲明數組外,還可以在一條語句中聲明數組
int[] myArray = new int[4];
還可以用數組初始化器為每個元素賦值:
int[] myArray = new int[4]{23,5,6,18};
使用花括弧還可以不用指定數組的大小,編譯器會自動統計數組的個數:
string[] strName = new string[]{“limits”,”fly”,”studion”};
還可以用下面簡化方式進行數組聲明:
string[] strName = {“limits”,”fly”,”studion”};
三. 訪問數組元素
在聲明和初始化數組後,就可以使用索引器訪問數組的元素了,數組只支援整型參數的索引器。通過索引器傳遞元素編號,就可以訪問數組;索引器是從0開始計數的,表示第一個數組元素,可以傳遞給索引器的的最大值是元素個數減1,因為索引是從0開始的。註:如果使用錯誤的索引器值(不存在的對應元素),就會拋出IndexOutOfRangeException類型的異常。
//初始化數組 int[] arrNumber = new int[] { 2, 4, 6, 8, 10, 12 }; //使用索引器訪問第二個元素int arr1 = arrNumber[1];
不知道數組元素的個數,可以在for語句中使用Length屬性來擷取每個元素:
int[] arrNumber = new int[] { 2, 4, 6, 8, 10, 12 };for (int i = 0; i < arrNumber.Length; i++){ Console.WriteLine(arrNumber[i]);}
另外一種方法是使用 foreach來讀取每個數組元素,效果跟for語句一樣:
int[] arrNumber = new int[] { 2, 4, 6, 8, 10, 12 };foreach (int item in arrNumber){ Console.WriteLine(item);}
四. 使用參考型別
除了聲明預定義類型的數組外,還可以聲明自訂類型的數組:
class Program { public class Student { //學生姓名的兩個自動屬性 public string firstName { get; set; } public string lastName { get; set; } //重寫ToString()方法 public override string ToString() { return string.Format("{0},{1}", firstName, lastName); } } static void Main(string[] args) { //聲明一個包含3個Student元素的數組 Student[] student = new Student[3]; student[0] = new Student { firstName = "Lim", lastName = "Deng" }; student[1] = new Student { firstName = "Yuchun", lastName = "Xiang" }; student[2] = new Student { firstName = "Pengfei", lastName = "Lai" }; //使用 foreach語句讀出每個Student元素 foreach (var item in student) { Console.WriteLine(item); }
}
結果如:
從上面例子可以看出Student是儲存在棧上的一個變數,改變數引用了儲存在託管堆上的Student元素對應的數組,這個數組足夠存放3個引用空間,數組中的每一個項都引用了Student對象,而這些Student對象都儲存在託管堆上。