作法:使用 foreach 存取命令列引數 (C# 程式設計指南)How to: Access Command-Line Arguments Using foreach (C# Programming Guide)

逐一查看陣列的另一種方法是使用 foreach 陳述式,如本例所示。Another approach to iterating over the array is to use the foreach statement as shown in this example. foreach 陳述式可用來逐一查看陣列、.NET Framework 集合類別,或實作 IEnumerable 介面的任何類別或結構。The foreach statement can be used to iterate over an array, a .NET Framework collection class, or any class or struct that implements the IEnumerable interface.

注意

在 Visual Studio 中執行應用程式時,您可以在專案設計工具、偵錯頁面中指定命令列引數。When running an application in Visual Studio, you can specify command-line arguments in the Debug Page, Project Designer.

範例Example

本例會示範如何使用 foreach 印出命令列引數。This example demonstrates how to print out the command line arguments using foreach.

// arguments: John Paul Mary
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);
        }
    }
}
/* Output:
    Number of command line parameters = 3
    John
    Paul
    Mary
*/

另請參閱See also