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

เมธอด Type.GetArrayRank() ใน C#

เมธอด Type.GetArrayRank() ใน C# ดึงจำนวนมิติ (Dimensions) ของอาร์เรย์

ไวยากรณ์

public virtual int GetArrayRank();

ตัวอย่างที่ 1: อาร์เรย์ 3 มิติ

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Type type = typeof(int[,,]);
        int arrRank = type.GetArrayRank();
        
        Console.WriteLine("Array Rank = {0}", arrRank);
    }
}

ผลลัพธ์

Array Rank = 3

ตัวอย่างที่ 2: อาร์เรย์ 8 มิติ และเปรียบเทียบ Type

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Type type = typeof(string[,,,,,,,]);
        Type type2 = typeof(string[,,,,,,,]);
        
        int arrRank = type.GetArrayRank();
        Console.WriteLine("Array Rank = {0}", arrRank);
        Console.WriteLine("Are both types equal? {0}", type.Equals(type2));
    }
}

ผลลัพธ์

Array Rank = 8
Are both types equal? True

หมายเหตุ: เมธอดนี้ทำงานได้เฉพาะกับ Type ที่เป็น Array เท่านั้น หากเรียกกับ Non-Array Type จะคืนค่า 0