Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để tìm số kích thước của một mảng trong C #?


Để tìm số thứ nguyên của một mảng, hãy sử dụng thuộc tính Xếp hạng.

arr.Rank

Đây, arr là mảng của chúng ta -

int[,] arr = new int[3,4];

Nếu bạn cũng muốn lấy các hàng và cột mà nó có, thì hãy sử dụng thuộc tính GetLength -

arr.GetLength(0);
arr.GetLength(1);

Sau đây là mã hoàn chỉnh -

Ví dụ

using System;

class Program {
   static void Main() {
      int[,] arr = new int[3,4];

      Console.WriteLine(arr.GetLength(0));
      Console.WriteLine(arr.GetLength(1));

      // Length
      Console.WriteLine(arr.Length);
      Console.WriteLine("Upper Bound: {0}",arr.GetUpperBound(0).ToString());
      Console.WriteLine("Lower Bound: {0}",arr.GetLowerBound(0).ToString());
      Console.WriteLine("Dimensions of Array : " + arr.Rank);
   }
}

Đầu ra

3
4
12
Upper Bound: 2
Lower Bound: 0
Dimensions of Array : 2