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

ดึงความกว้างและความสูงของอาร์เรย์ 3 มิติใน C#


ภาพรวม

สำหรับอาร์เรย์ 3 มิติ int[,,] arr = new int[3, 4, 5] สามารถใช้ GetLength() ดึงขนาดแต่ละมิติ โดยมักเรียกมิติ 0 ว่า "แถว" (rows/ความสูง) และมิติ 1 ว่า "คอลัมน์" (columns/ความกว้าง)

รูปแบบการใช้งาน

int[,,] arr = new int[3, 4, 5];
int rows = arr.GetLength(0);    // 3 - ความสูง/แถว
int cols = arr.GetLength(1);    // 4 - ความกว้าง/คอลัมน์
int depth = arr.GetLength(2);   // 5 - ความลึก/มิติที่ 3

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

using System;

class Program
{
    static void Main()
    {
        int[,,] arr = new int[3, 4, 5];
        Console.WriteLine(arr.GetLength(0)); // 3
        Console.WriteLine(arr.GetLength(1)); // 4
        Console.WriteLine(arr.GetLength(2)); // 5
    }
}

ผลลัพธ์

3
4
5

การวนลูปอาร์เรย์ 3 มิติ

for (int i = 0; i < arr.GetLength(0); i++)
    for (int j = 0; j < arr.GetLength(1); j++)
        for (int k = 0; k < arr.GetLength(2); k++)
            Console.WriteLine(arr[i, j, k]);

หมายเหตุ

คำว่า "width" และ "height" ใช้ได้ชัดเจนกับอาร์เรย์ 2 มิติ สำหรับ 3 มิติ ควรใช้ "rows, columns, depth" หรือ "dimension 0, 1, 2" จะชัดเจนกว่า