C# 数组 - GetLength() 方法

C# 数组 GetLength() 方法用于返回一个 32 位整数,表示指定维度数组中可用元素的数量。

如果维度为零或大于或等于秩,此方法将抛出 IndexOutOfRangeException

语法

以下是 C# 数组 GetLength() 方法的语法 -

public int GetLength(int dimension);

参数

此方法接受以下参数 -

  • dimension:表示需要确定长度的数组的从零开始的维度。

返回值

此方法返回一个 32 位整数,表示指定数组中元素的数量。

示例 1:显示整数数组的长度

这是 GetLength() 方法的基本示例,用于显示数组中存在的元素数量 -

using System;
class Program {
   static void Main() {
     
      int[] Number = new int[] {1, 2, 3, 4, 5};
   
      // 获取长度
      int length = Number.GetLength(0);
   
      Console.WriteLine("Length of the Array: " + length);
   }
}

输出

以下是输出 -

Length of the Array: 5

示例 2:查找二维数组的长度

让我们创建一个示例,使用 GetLength() 方法显示二维数组的行数和列数 -

using System;
class Program {
   static void Main() {
      int[,] matrix = {
         { 1, 2, 3 },
         { 4, 5, 6 },
         { 7, 8, 9 }
      };

      // 获取行数(维度 0)
      int rows = matrix.GetLength(0);

      // 获取列数(维度 1)
      int columns = matrix.GetLength(1);

      Console.WriteLine($"Rows: {rows}, Columns: {columns}");
   }
}

输出

以下是输出 -

Rows: 3, Columns: 3

Example 3: Get the Dimension of 3D-Array

Let's see another example of theGetLength()method to display the number of elements of each dimension in the array −

using System;
class Program {
   static void Main() {
      int[,,] cube = {
         { { 1, 2 }, { 3, 4 } },
         { { 5, 6 }, { 7, 8 } }
      };

        // 获取第一维的长度
        int dim0 = cube.GetLength(0);
        
        // 获取第二维的长度
        int dim1 = cube.GetLength(1);
        
        // 获取第三维的长度
        int dim2 = cube.GetLength(2);

      	Console.WriteLine($"Dimension 0: {dim0}, Dimension 1: {dim1}, Dimension 2: {dim2}");
   }
}

输出

以下是输出 -

Dimension 0: 2, Dimension 1: 2, Dimension 2: 2

示例 4:动态访问数组维度

我们来看看 GetLength() 方法的另一个版本。在这个版本中,我们使用 Rank 属性来确定维度的数量。

using System;
class Program {
   static void Main(){
      double[,] table = new double[4, 5];

      for (int i = 0; i < table.Rank; i++){
         Console.WriteLine($"Length of dimension {i}: {table.GetLength(i)}");
      }
   }
}

输出

以下是输出 -

Length of dimension 0: 4
Length of dimension 1: 5

csharp_array_class.html