【C#】【溫故知新】多維數組之矩形數組與交錯數組

數組分爲一維數組與多維數組,多維數組又分爲矩形數組與交錯數組。

矩形數組:

 某個維度的所有子數組長度相同。(與矩陣類似)

    int[,,] array1 = new int[2, 3, 2];
    int[,,] array2 = new int[,,]
        {
            { { 1, 1 },{ 2, 2 },{ 3, 3 } },
            { { 4, 4 },{ 5, 5 },{ 6, 6 } }
        };

交錯數組:

 每個子數組都是獨立數組,可以長度不同。(是多層數組的嵌套)

    //只能初始化頂層數組,即不能是new int[2][3],子數組需要獨立創建
    int[][] array3 = new int[2][];

    private void Start()
    {
        array3[0] = new int[3];
        array3[1] = new int[4];
    }

 System.Array屬性/方法:

    private void Start()
    {
        int[,,] array = new int[2, 3, 2]
        {
            { { 1, 1 },{ 2, 2 },{ 3, 3 } },
            { { 4, 4 },{ 5, 5 },{ 6, 6 } }
        };

        //獲取數組維度
        Debug.Log(array.Rank);          // 3
        //獲取數組中所有維度的元素數量和
        Debug.Log(array.Length);        // 12
        //獲取指定維度子數組的長度
        Debug.Log(array.GetLength(0));  // 2
        Debug.Log(array.GetLength(1));  // 3
        Debug.Log(array.GetLength(2));  // 2
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章