天天看點

C#進階程式設計學習筆記(1)

1).在C#中,數組是引用類型。C#的數組類型比較靈活,可以在聲明數組時不進行初始化,這樣以後就可以動态地 指定其大小。利用這種技術,可以建立一個空引用,以後再使用new關鍵字把這個引用指向請求動态配置設定的記憶體位置。

    例如:int[] Integers;

              Integers = new int[32];      

 同時,在c和C++中,數組的一個優點是可以在花括号中為資料提供一組初始值的寫死清單。C#保留了這種友善的特性:

            string[] String={"first element","second element","third element"};

          在C#中,等價于:

           string[] String=new string[] {"first element","second element","third element"};

在初始化數組時,有幾個應避免的問題。例如:

一、不能用變量設定數組應包含多少個元素

         int len = 3;

         string[] String = new string[len] {"first element","second element","third element"};  //錯誤

         正确的聲明:const int len = 3;

二、如果希望數組的長度是動态變化的,或者數組在運作期間其長度會增加。就必須建立ArrayList對象的一個執行個體,該對象在System.Collections名稱空間上。

三、類也可以儲存在資料中,具體可見(A 為一個類)

 static void Main(string[] args)

        {

            A[] ab;

            ab = new A[3];  //隻是配置設定空間

            ab[1] = new A(); //執行個體化,即構造函數執行

            Console.WriteLine(ab[1].a);

            Console.ReadLine();

        }

四、因為數組本身也是類,如果數組的元素是預定義類型,則可以使用Sort方法把數組按升序排列。

       Array.Sort(string)  //string為數組名

      也可以使用System.Array.Sort方法和Icompare接口給資料排序。