int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);
MSDN中指出,GetLength返回元素数量,而GetUpperBound确定最大索引。但是,由于数组已经初始化了每个索引的元素,这两者怎么可能不同呢?
int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);
MSDN中指出,GetLength返回元素数量,而GetUpperBound确定最大索引。但是,由于数组已经初始化了每个索引的元素,这两者怎么可能不同呢?
看一下这个(很少使用的)方法。来自 文档:
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
创建指定类型和维度长度、指定下限的多维数组。
使用它,你可以创建一个索引从 -5 ... +5
的数组。如果您曾经使用过这种类型的数组,则 GetUpperBound()
比 GetLength()-1
更有用处。还存在一个 GetLowerBound()
。
但是 C# 对这种类型的数组的支持比较低,您不能使用 []
运算符。只有与 Array.GetValue() 和 SetValue() 方法相结合时,您才需要使用这些方法。
Array.Length
返回数组的长度(元素数量),需要从中减去1才能获得上界。
Array.GetUpperBound(0)
返回数组的上界,您可以直接使用它。
通常情况下,array.GetUpperBound(0) = array.Length - 1
,但是由于我们可以创建具有非零下限的数组,因此这并不总是正确的。
GetUpperBound
返回数组的最高索引,而GetLength
返回数组的元素数量。
也就是说,GetUpperBound = GetLength - 1
。
我知道这是一个老问题,但我认为值得强调的是GetUpperBound返回指定维度的上边界。对于多维数组来说,这很重要,因为在这种情况下,两个函数是不等价的。
// Given a simple two dimensional array
private static readonly int[,] USHolidays =
{
{ 1, 1 },
{ 7, 4 },
{ 12, 24 },
{ 12, 25 }
};
Length属性会输出8,因为数组中有8个元素。
Console.WriteLine(USHolidays.Length);
然而,GetUpperBound()函数将输出3作为第一维度的上限边界是3。换句话说,我可以循环遍历数组索引0、1、2和3。
Console.WriteLine(USHolidays.GetUpperBound(0));
for (var i = 0; i <= USHolidays.GetUpperBound(0); i++)
{
Console.WriteLine("{0}, {1}", USHolidays[i, 0], USHolidays[i, 1]);
}