System.Array.GetLength 方法

方法描述

获取一个 32 位整数,该整数表示 Array 的指定维中的元素数。

语法定义(C# System.Array.GetLength 方法 的用法)

public int GetLength(
	int dimension
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
dimension System-Int32 Array 的从零开始的维度,其长度需要确定。
返回值 System.Int32 一个 32 位整数,它表示指定维中的元素数。

提示和注释

GetLength(0) 为 GetLength 的一个示例,它返回 Array 的第一维中的元素个数。

此方法的运算复杂度是 O(1)。

System.Array.GetLength 方法例子

下面的示例演示如何使用 GetLength 显示两个具有不同秩的数组的尺寸。

using System;

public class SamplesArray
{
    public static void Main()
    {
        // make a single dimension array
        Array MyArray1 = Array.CreateInstance(typeof(int), 5);

        // make a 3 dimensional array
        Array MyArray2 = Array.CreateInstance(typeof(int), 5, 3, 2);

        // make an array container
        Array BossArray = Array.CreateInstance(typeof(Array), 2);
        BossArray.SetValue(MyArray1, 0);
        BossArray.SetValue(MyArray2, 1);

        int i = 0, j, rank;
        foreach (Array anArray in BossArray)
        {
            rank = anArray.Rank;
            if (rank > 1)
            {
                Console.WriteLine("Lengths of {0:d} dimension array[{1:d}]", rank, i);
                // show the lengths of each dimension
                for (j = 0; j < rank; j++)
                {
                    Console.WriteLine("    Length of dimension({0:d}) = {1:d}", j, anArray.GetLength(j));
                }
            }
            else
            {
                Console.WriteLine("Lengths of single dimension array[{0:d}]", i);
            }
            // show the total length of the entire array or all dimensions
            Console.WriteLine("    Total length of the array = {0:d}", anArray.Length);
            Console.WriteLine();
            i++;
        }
    }
}

/*
This code produces the following output:

Lengths of single dimension array[0]
    Total length of the array = 5

Lengths of 3 dimension array[1]
    Length of dimension(0) = 5
    Length of dimension(1) = 3
    Length of dimension(2) = 2
    Total length of the array = 30
*/

异常

异常 异常描述
IndexOutOfRangeException
  • dimension 小于零。
  • dimension 等于或大于 Rank。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。