Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิหาห Rank (มิติ) ของ Array ใน C#

ใช้ Property Rank ของ Array เพื่อหาจำนวนมิติ (Dimensions)

Syntax

int dimensions = arr.Rank;

โค้ดตัวอย่างเต็ม

using System;

class Program
{
    static void Main()
    {
        // 2D Array: 3 แถว, 4 คอลัมน์
        int[,] arr = new int[3, 4];
        
        Console.WriteLine("Rows (GetLength 0): " + arr.GetLength(0));    // 3
        Console.WriteLine("Cols (GetLength 1): " + arr.GetLength(1));    // 4
        Console.WriteLine("Total Elements (Length): " + arr.Length);     // 12
        Console.WriteLine("Upper Bound Dim 0: " + arr.GetUpperBound(0)); // 2 (0-based)
        Console.WriteLine("Lower Bound Dim 0: " + arr.GetLowerBound(0)); // 0
        Console.WriteLine("Dimensions (Rank): " + arr.Rank);             // 2
    }
}

ผลลัพธ์

Rows (GetLength 0): 3
Cols (GetLength 1): 4
Total Elements (Length): 12
Upper Bound Dim 0: 2
Lower Bound Dim 0: 0
Dimensions (Rank): 2

Properties สำคัญของ Array

Propertyคำอธิบายตัวอย่าง (int[3,4])
Rankจำนวนมิติ2
Lengthจำนวน Elements ทั้งหมด12
GetLength(dimension)ขนาดในมิติที่ระบุ (0-based)GetLength(0)=3, GetLength(1)=4
GetUpperBound(dimension)ดัชนีสูงสุดในมิตินั้นGetUpperBound(0)=2
GetLowerBound(dimension)ดัชนีต่ำสุดในมิตินั้น (มักเป็น 0)GetLowerBound(0)=0

Jagged Array

int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[1];

Console.WriteLine(jagged.Rank); // 1 (Jagged Array เป็น 1D Array ของ Array)