用户登录
用户注册

分享至

C#中用foreach语句遍历数组及将数组作为参数的用法

  • 作者: 獬豸烤肉
  • 来源: 51数据库
  • 2021-10-16

对数组使用 foreach
c#提供 foreach 语句。 该语句提供一种简单、明了的方法来循环访问数组或任何可枚举集合的元素。 foreach 语句按数组或集合类型的枚举器返回的顺序处理元素,该顺序通常是从第 0 个元素到最后一个元素。 例如,以下代码创建一个名为 numbers 的数组,并使用 foreach 语句循环访问该数组:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
  system.console.write("{0} ", i);
}
// output: 4 5 6 1 2 3 -2 -1 0


借助多维数组,你可以使用相同的方法来循环访问元素,例如:

int[,] numbers2d = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// or use the short form:
// int[,] numbers2d = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2d)
{
  system.console.write("{0} ", i);
}

输出:

9 99 3 33 5 55

但对于多维数组,使用嵌套的 for 循环可以更好地控制数组元素。

将数组作为参数传递
数组可作为实参传递给方法形参。由于数组是引用类型,因此方法可以更改元素的值。
将一维数组作为参数传递
可以将初始化的一维数组传递给方法。例如,下面的语句将数组发送到 print 方法。

int[] thearray = { 1, 3, 5, 7, 9 };
printarray(thearray);

下面的代码显示 print 方法的部分实现。

void printarray(int[] arr)
{
  // method code.
}

您可以在一个步骤中初始化和传递新数组,如下面的示例所示。

printarray(new int[] { 1, 3, 5, 7, 9 });

示例
说明
在下面的示例中,将初始化一个字符串数组并将其作为参数传递到字符串的 printarray 方法。该方法显示数组的元素。接下来,调用 changearray 和 changearrayelement 方法以演示通过值发送数组参数时不会阻止更改这些数组元素。
代码

class arrayclass
{
  static void printarray(string[] arr)
  {
    for (int i = 0; i < arr.length; i++)
    {
      system.console.write(arr[i] + "{0}", i < arr.length - 1 ? " " : "");
    }
    system.console.writeline();
  }

  static void changearray(string[] arr)
  {
    // the following attempt to reverse the array does not persist when
    // the method returns, because arr is a value parameter.
    arr = (arr.reverse()).toarray();
    // the following statement displays sat as the first element in the array.
    system.console.writeline("arr[0] is {0} in changearray.", arr[0]);
  }

  static void changearrayelements(string[] arr)
  {
    // the following assignments change the value of individual array 
    // elements. 
    arr[0] = "sat";
    arr[1] = "fri";
    arr[2] = "thu";
    // the following statement again displays sat as the first element
    // in the array arr, inside the called method.
    system.console.writeline("arr[0] is {0} in changearrayelements.", arr[0]);
  }

  static void main()
  {
    // declare and initialize an array.
    string[] weekdays = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };

    // pass the array as an argument to printarray.
    printarray(weekdays);

    // changearray tries to change the array by assigning something new
    // to the array in the method. 
    changearray(weekdays);

    // print the array again, to verify that it has not been changed.
    system.console.writeline("array weekdays after the call to changearray:");
    printarray(weekdays);
    system.console.writeline();

    // changearrayelements assigns new values to individual array
    // elements.
    changearrayelements(weekdays);

    // the changes to individual elements persist after the method returns.
    // print the array, to verify that it has been changed.
    system.console.writeline("array weekdays after the call to changearrayelements:");
    printarray(weekdays);
  }
}

输出:

sun mon tue wed thu fri sat
arr[0] is sat in changearray.
array weekdays after the call to changearray:
sun mon tue wed thu fri sat

arr[0] is sat in changearrayelements.
array weekdays after the call to changearrayelements:
sat fri thu wed thu fri sat

将多维数组作为参数传递
可采用与传递一维数组相同的方式将初始化的多维数组传递给方法。

int[,] thearray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
print2darray(thearray);

下面的代码显示 print 方法的部分声明,该方法接受一个二维数组作为其参数。

void print2darray(int[,] arr)
{
  // method code.
}

您可以在一个步骤中初始化和传递新数组,如下面的示例所示。

print2darray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

示例
说明
在下面的示例中,将初始化一个二维整数数组并将其传递到 print2darray 方法。该方法显示数组的元素。
代码

class arrayclass2d
{
  static void print2darray(int[,] arr)
  {
    // display the array elements.
    for (int i = 0; i < arr.getlength(0); i++)
    {
      for (int j = 0; j < arr.getlength(1); j++)
      {
        system.console.writeline("element({0},{1})={2}", i, j, arr[i, j]);
      }
    }
  }
  static void main()
  {
    // pass the array as an argument.
    print2darray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

    // keep the console window open in debug mode.
    system.console.writeline("press any key to exit.");
    system.console.readkey();
  }
}

输出:

element(0,0)=1
element(0,1)=2
element(1,0)=3
element(1,1)=4
element(2,0)=5
element(2,1)=6
element(3,0)=7
element(3,1)=8

软件
前端设计
程序设计
Java相关