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

所属分类: 软件编程 / C#教程 阅读数: 75
收藏 0 赞 0 分享

对数组使用 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

更多精彩内容其他人还在看

c#开发word批量转pdf源码分享

已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF,看下面的实例源码吧
收藏 0 赞 0 分享

c# xml API操作的小例子

这篇文章主要介绍了c# xml API操作的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c#唯一值渲染实例代码

这篇文章主要介绍了c#唯一值渲染实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

淘宝IP地址库采集器c#代码

这篇文章主要介绍了淘宝IP地址库采集器c#代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C#在后台运行操作(BackgroundWorker用法)示例分享

BackgroundWorker类允许在单独的专用线程上运行操作。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题,下面看示例
收藏 0 赞 0 分享

c#文本加密程序代码示例

这是一个加密软件,但只限于文本加密,加了窗口控件的滑动效果,详细看下面的代码
收藏 0 赞 0 分享

c#生成站点地图(SiteMapPath)文件示例程序

这篇文章主要介绍了c#生成站点地图(SiteMapPath)文件的示例,大家参考使用
收藏 0 赞 0 分享

C# 键盘Enter键取代Tab键实现代码

这篇文章主要介绍了C# 键盘Enter键取代Tab键实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm导出Excel方法介绍

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
收藏 0 赞 0 分享

C#串口通信程序实例详解

在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports,创建C#串口通信程序的具体实现是如何的呢?让我们开始吧
收藏 0 赞 0 分享
查看更多