C# 中的数组大小(长度) [英] Array Size (Length) in C#

查看:27
本文介绍了C# 中的数组大小(长度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中确定数组的大小(长度/项目数)?

How can I determine size of an array (length / number of items) in C#?

推荐答案

如果是一维数组a,

a.Length

将给出a的元素数量.

如果b是一个矩形多维数组(例如int[,] b = new int[3, 5];)

If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5];)

b.Rank

将给出维数 (2) 和

will give the number of dimensions (2) and

b.GetLength(dimensionIndex)

将获得任何给定维度的长度(维度的基于 0 的索引 - 所以 b.GetLength(0) 是 3 并且 b.GetLength(1)是 5).

will get the length of any given dimension (0-based indexing for the dimensions - so b.GetLength(0) is 3 and b.GetLength(1) is 5).

请参阅 System.Array 文档 了解更多信息.

See System.Array documentation for more info.

正如@Lucero 在评论中指出的那样,有一个锯齿状数组"的概念,它实际上只不过是(通常是一维)数组的一维数组.

As @Lucero points out in the comments, there is a concept of a "jagged array", which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.

例如,可以有以下内容:

For example, one could have the following:

int[][] c = new int[3][];
c[0] = new int[] {1, 2, 3};
c[1] = new int[] {3, 14};
c[2] = new int[] {1, 1, 2, 3, 5, 8, 13};

注意 c 的 3 个成员都有不同的长度.在这种情况下,和前面一样,c.Length 将表示c、(3) 和c[0].Length 的元素个数,c[1].Lengthc[2].Length 将分别为 3、2 和 7.

Note that the 3 members of c all have different lengths. In this case, as before c.Length will indicate the number of elements of c, (3) and c[0].Length, c[1].Length, and c[2].Length will be 3, 2, and 7, respectively.

这篇关于C# 中的数组大小(长度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆