循环访问数组的另一种方法是使用 foreach 语句,如下面的示例所示。foreach 语句可以用于循环访问数组、.NET Framework 集合类或任何实现 
示例
下面的示例演示如何使用 foreach 输出命令行参数。
| C# |  复制代码 | 
|---|---|
// arguments: John Paul Mary  | |
| C# |  复制代码 | 
|---|---|
class CommandLine2
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Number of command line parameters = {0}", args.Length);
        foreach (string s in args)
        {
            System.Console.WriteLine(s);
        }
    }
}
 | |
输出
Number of command line parameters = 3 John Paul Mary  | |
请参见
任务
如何:显示命令行参数(C# 编程指南)参考
foreach,in(C# 参考)Main() 和命令行参数(C# 编程指南)
Main() 返回值(C# 编程指南)