数组的GetUpperBound()和GetLowerBound()函数

Nar*_*dra 9 .net c# arrays

任何人都可以告诉这两个功能有什么作用?它们采用一个整数参数,它被称为维度.但是这个整数的值如何改变输出呢?

下面是我跑的一个例子.

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
Run Code Online (Sandbox Code Playgroud)

知道为什么GetLowerBound()总是返回0?如果这总是返回0那么为什么我们需要调用这个方法?

Dmi*_*nko 20

可能是一些例子让你明白这个话题

我们GetUpperBound()用来找出给定维度的数组的上界,如下所示:

  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); 
Run Code Online (Sandbox Code Playgroud)

通常,GetLowerBound()返回0,因为默认情况下数组从零开始,但在极少数情况下它们不是:

  // 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); 
Run Code Online (Sandbox Code Playgroud)

典型的循环使用GetLowerBoundGetUpperBound

  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];
        ...
      }
Run Code Online (Sandbox Code Playgroud)


Iri*_*ium 5

用于GetUpper/LowerBound()指定维度的整数参数.

一些例子:

// One-dimensional array
var oneD = new object[5];
Console.WriteLine("Dimension 0 Lower bound: {0}", oneD.GetLowerBound(0)) // Outputs "Dimension 0 Lower bound: 0"
Console.WriteLine("Dimension 0 Upper bound: {0}", oneD.GetUpperBound(0)) // Outputs "Dimension 0 Upper bound: 4"

// Two-dimensional array
var twoD = new object[5,10];
Console.WriteLine("Dimension 0 Lower bound: {0}", twoD.GetLowerBound(0)) // Outputs "Lower bound: 0"
Console.WriteLine("Dimension 0 Upper bound: {0}", twoD.GetUpperBound(0)) // Outputs "Upper bound: 4"
Console.WriteLine("Dimension 1 Lower bound: {0}", twoD.GetLowerBound(1)) // Outputs "Lower bound: 0"
Console.WriteLine("Dimension 1 Upper bound: {0}", twoD.GetUpperBound(1)) // Outputs "Upper bound: 9"
Run Code Online (Sandbox Code Playgroud)

虽然在C#中定义的数组具有下限= 0且上限=长度-1,但来自其他来源(例如COM互操作)的数组可以具有不同的边界,因此例如使用Excel互操作的数组将熟悉具有下限=的数组= 1,上限=长度.