array.GetLength(0)和array.GetUpperBound之间差(0) [英] Difference between array.GetLength(0) and array.GetUpperBound(0)
问题描述
什么是这两种方法之间的差异,当你想使用一个不是其他的?
INT [,]数组=新INT [4,3]。
INT length0 = array.GetLength(0);
INT upperbound0 = array.GetUpperBound(0);
MSDN说,对GetLength返回的元素数,其中作为GetUpperBound确定最大索引,但怎么会这样,因为不同的阵列与每个索引元素初始化?
看看这(很少使用)的方法。从 MSDN :
公共静态数组的CreateInstance(类型元素类型,INT []的长度,INT [] lowerBounds)
创建指定类型和尺寸长度多维数组,与指定的下限。
块引用>有了它,你可以创建索引,例如数组从
-5 ... +5
。如果你曾经使用这种类型的数组,那么GetUpperBound()
一下子变成了很多比对GetLength()更有用 - 1
。此外,还存在一个GetLowerBound()
。所以,正式,我们所有的
的for(int i = 0; I<则为a.length;我++)
回路应
的for(int i = a.GetLowerBound(); I< = a.GetUpperBound();我++)
但请不要这么做。
What is the difference between these two methods and when would you use one instead of the other?
int[,] array = new int[4,3]; int length0 = array.GetLength(0); int upperbound0 = array.GetUpperBound(0);
MSDN says that GetLength return the number of elements where as GetUpperBound determine the max index, but how could this be different since arrays are initialized with elements for each index?
解决方案Take a look at this (rarely used) method. From MSDN:
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.
With it, you can create an array with indices from
-5 ... +5
for example. If you ever use this kind of array, thenGetUpperBound()
suddenly becomes a lot more useful thanGetLength()-1
. There also exists aGetLowerBound()
.So, formally, all our
for(int i = 0; i < a.Length; i++)
loops should be
for(int i = a.GetLowerBound(); i <= a.GetUpperBound(); i++)
but please don't do that.
这篇关于array.GetLength(0)和array.GetUpperBound之间差(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!