C#學習筆記 ----數組

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   strong   ar   for   div   

如果需要使用同一類型的多個對象,就可以使用集合和數組

 

數組是參考型別

 

簡單數組

多維陣列

int[,,] threedim = {    {{1,2},{3,4}},    {{5,6},{7,8}},    {{9,10},{11,12}}    };Console.WriteLine(threedim[0,1,1]);

 

鋸齒數組

int[][] jagged = new int[3][];jagged[0] = new int[2]{1,2};jagged[1] = new int[6]{3,4,5,6,7,8};jagged[2] = new int[3]{9,10,11};

 

Array類

Array類是一個抽象類別,所以不能使用建構函式來建立數組

可以使用靜態方法CreateInstance()建立數組

 

複製數組,會使數組實現ICloneable介面。這個介面定義的Clone()方法會建立數組的淺表副本

 

Array類使用QuickSort演算法對數組中元素進行排序。Sort()方法需要數組中的元素實現IComparable介面

 

public enum PersonCompareType{    FirstName,    LastName}public class PersonComparer:IComparer<Person>{    private PersonCompareType compareType;        public PersonComparer(PersonCompareType compareType)    {        this.compareType = compareType;    }    public int Compare(Person x,Person y)    {        if(x == null) throw new ArgumentNullException("x");        if(y == null) throw new ArgumentNullException("y");        switch(compareType)        {            case PersonCompareType.FirstName:                return x.FirstName.CompareTo(y.FirstName);            case PersonCompareType.LastName:                return x.LastName.CompareTo(y.LastName);            default:                throw new ArgumentException(                    "unexpected compare type");        }    }}Array.Sort(persons,    new PersonComparer(PersonCompareType.FirstName));foreach(var p in persons){    Console.WriteLine(p);}

 

ArraySegment<T>

結構ArraySegment<T>表示數組的一段

int[] ar1 = {1,4,5,11,13,18};int[] ar2 = {3,4,5,18,21,27,33};var segments = new ArraySegment<int> [2]{    new ArraySegment<int> (ar1,0,3),    new ArraySegment<int> (ar2,3,3)};

 

枚舉

在foreach語句中使用枚舉,可以迭代集合中的元素,且無需知道集合中的元素個數。

foreach語句使用了一個列舉程式

 

數組或集合實現帶GetEumerator()方法的IEumerable介面

GetEumerator()方法返回一個實現IEumerable介面的枚舉。

 

foreach語句使用IEnumerable介面的方法和屬性,迭代集合中的所有元素

 

C#的foreach語句不會解析為IL代碼中的foreach語句

C#的編譯器會把foreach語句轉換為IEnumerable介面的方法和屬性

 

yield語句

yield return 語句返回集合的一個元素,並移動到下一個元素上

yield break 停止迭代

 

元組
數組合并了相同類型的對象,而元組合并了不同類型的對象。

數組和元組都實現介面IStructuralEquatable和IStructuralComparable。

C#學習筆記 ----數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.