数组的GetUpperBound()和GetLowerBound()函数 [英] GetUpperBound() and GetLowerBound() function for array
问题描述
谁能告诉我这两个功能是做什么的?他们采用一个整数参数,该参数被告知是尺寸.但是这个整数的值如何改变输出?
Can anyone please tell what does the two functions do? They take an integer argument which is told to be dimension. But how does the value of this integer changes the output?
下面是我运行的示例.
int[, ,] intMyArr = {{{ 7, 1, 3, 4 }, { 2, 9, 6, 5 } }, { { 7, 1, 3, 4 }, { 2, 9, 6, 5 }}};
Console.WriteLine(intMyArr.GetUpperBound(0)); // Output is 1
Console.WriteLine(intMyArr.GetUpperBound(1)); // Output is 1
Console.WriteLine(intMyArr.GetUpperBound(2)); // Output is 3
Console.WriteLine(intMyArr.GetLowerBound(0)); // Output is 0
Console.WriteLine(intMyArr.GetLowerBound(1)); // Output is 0
Console.WriteLine(intMyArr.GetLowerBound(2)); // Output is 0
有人知道为什么GetLowerBound()总是返回0吗?如果它总是返回0,那为什么我们要 需要调用此方法吗?
Any idea why GetLowerBound() is always returning 0? If this always returns 0 then why do we need to call this method?
推荐答案
也许有一些例子可以使您的话题清楚
May be some examples make the topic clear for you
我们使用GetUpperBound()
来找出给定尺寸的数组的上限,
像这样:
We use GetUpperBound()
to find out the upper bound of an array for given dimension,
like that:
int[,,] A = new int[7, 9, 11];
// Returns 6: 0th dimension has 7 items, and so upper bound is 7 - 1 = 6;
int upper0 = A.GetUpperBound(0);
// Returns 8: 0th dimension has 7 items, 1st - 9 and so upper bound is 9 - 1 = 8;
int upper1 = A.GetUpperBound(1);
// Returns 10: 0th dimension has 7 items, 1st - 9, 2nd - 11 and so upper bound is 11 - 1 = 10;
int upper2 = A.GetUpperBound(2);
通常,GetLowerBound()
返回 0 ,因为默认情况下数组是从零开始的,
但在极少数情况下,它们不是:
usually, GetLowerBound()
returns 0, since arrays are zero-based by default,
but in some rare cases they are not:
// A is [17..21] array: 5 items starting from 17
Array A = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 17 });
// Returns 17
int lower = A.GetLowerBound(0);
// Returns 21
int upper = A.GetUpperBound(0);
使用GetLowerBound
和GetUpperBound
的典型循环是
int[] A = ...
for(int i = A.GetLowerBound(0); i <= A.GetUpperBound(0); ++i) {
int item = A[i];
...
}
// ... or multidimension
int[,,] A = ...;
for (int i = A.GetLowerBound(0); i <= A.GetUpperBound(0); ++i)
for (int j = A.GetLowerBound(1); j <= A.GetUpperBound(1); ++j)
for (int k = A.GetLowerBound(2); k <= A.GetUpperBound(2); ++k) {
int item = A[i, j, k];
...
}
这篇关于数组的GetUpperBound()和GetLowerBound()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!