Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# array.GetLength(0)和array.GetUpperBound(0)之间的差异_C#_Arrays_Multidimensional Array - Fatal编程技术网

C# array.GetLength(0)和array.GetUpperBound(0)之间的差异

C# array.GetLength(0)和array.GetUpperBound(0)之间的差异,c#,arrays,multidimensional-array,C#,Arrays,Multidimensional Array,这两种方法的区别是什么?你什么时候会使用其中一种而不是另一种 int[,] array = new int[4,3]; int length0 = array.GetLength(0); int upperbound0 = array.GetUpperBound(0); MSDN说GetLength返回元素的数量,其中GetUpperBound决定了最大索引,但既然数组是用每个索引的元素初始化的,那么这又有什么不同呢?数组。Length返回所需数组的长度(元素数量) 从中减去1得到上界 Arr

这两种方法的区别是什么?你什么时候会使用其中一种而不是另一种

int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);

MSDN说GetLength返回元素的数量,其中GetUpperBound决定了最大索引,但既然数组是用每个索引的元素初始化的,那么这又有什么不同呢?

数组。Length
返回所需数组的长度(元素数量) 从中减去1得到上界

Array.GetUpperBound(0)
返回数组的上限,您可以使用它
原样。

GetUpperBound
返回数组中的最高索引,
GetLength
返回数组的元素数

Console.WriteLine(USHolidays.Length);
i、 GetUpperBound=GetLength-1

看看这个(很少使用的)方法。发件人:

公共静态数组CreateInstance(Type elementType,int[]length,int[]lowerBounds)

创建具有指定类型和维度长度以及指定下限的多维数组

使用它,您可以使用
-5+5
。如果您曾经使用过这种数组,那么
GetUpperBound()
突然变得比
GetLength()-1
有用得多。还有一个
GetLowerBound()


但是对这种数组的C#支持很低,不能使用
[]
。您只需要将这些方法与Array.GetValue()和SetValue()方法结合使用。

通常,
Array.GetUpperBound(0)=Array.Length-1
,但由于我们可以创建具有非零下限的数组,这并不总是正确的。

如果数组的下限为0,则可以使用其中任何一个,而不会产生任何混淆,但我建议使用array.length-1,因为它被广泛使用。但是,如果数组的下限小于0,则应使用array.GetUpperBound(0),因为在本例中为array.length-1!=array.getUpperBound(0)

我意识到这是一个老问题,但我认为值得强调的是,返回指定维度的上边界。这对于多维数组很重要,因为在这种情况下,这两个函数并不等价

// 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]);
}
Console.WriteLine(USHolidays.GetUpperBound(0));

对于(var i=0;我通常是这样。但这不是它被提供的原因。+1对于你的答案,我不知道你可以在索引0以外的地方开始一个数组!你假设下限总是零。它不是。“但是请不要这样做。”。如果你确定数组的边界,为什么不呢?我只会在我不确定边界的情况下使用它。