Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểu phần tử của Jagged Array trong C#

Jagged Array = mảng của mảng (int[][]). Phần tử là reference type (mảng con), khởi tạo mặc định null.

Khai báo

int[][] marks; // Chỉ khai báo, null

Khởi tạo

int[][] marks = new int[5][]; // 5 hàng, mỗi hàng null
marks[0] = new int[] { 40, 57 };
marks[1] = new int[] { 34, 55 };
// ...

Hoặc initializer:

int[][] marks = new int[][]
{
    new int[] { 90, 95 },
    new int[] { 89, 94 },
    new int[] { 78, 87 },
    new int[] { 76, 68 },
    new int[] { 98, 91 }
};

Ví dụ

using System;

namespace MyApplication
{
    class MyDemoClass
    {
        static void Main(string[] args)
        {
            int[][] marks = new int[][]
            {
                new int[] { 90, 95 },
                new int[] { 89, 94 },
                new int[] { 78, 87 },
                new int[] { 76, 68 },
                new int[] { 98, 91 }
            };
            
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 2; j++)
                    Console.WriteLine("marks[{0}][{1}] = {2}", i, j, marks[i][j]);
            }
            Console.ReadKey();
        }
    }
}

Kết quả

marks[0][0] = 90  marks[0][1] = 95
marks[1][0] = 89  marks[1][1] = 94
marks[2][0] = 78  marks[2][1] = 87
marks[3][0] = 76  marks[3][1] = 68
marks[4][0] = 98  marks[4][1] = 91

Jagged vs Rectangular

Đặc điểmJagged ([][])Rectangular ([,])
Row lengthKhác nhau đượcCùng nhau
MemoryNon-contiguousContiguous block
Accessmarks[i][j]marks[i,j]
GCNhiều object nhỏ1 object lớn
PerformanceCache miss nhiều hơnCache friendly