在 C# 中,Main 方法的 string[] args 參數用於接收命令列傳入的引數。以下範例示範如何列印所有參數及其索引:
// CommandLine\cmdline1.cs
using System;
public class CommandLine
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}", args.Length);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
}
}
若輸入 cmdline1 A B C,輸出結果為:
Number of command line parameters = 3
Arg[0] = [A]
Arg[1] = [B]
Arg[2] = [C]
格式化字串 {0} 是佔位符,對應後方傳入的第一個參數(此處為 i),{1} 對應第二個參數(args[i])。
foreach 陳述式能自動遍歷陣列或集合中的每個元素,無需手動管理索引:
// CommandLine\cmdline2.cs
using System;
public class CommandLine2
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}", args.Length);
foreach (string s in args)
{
Console.WriteLine(s);
}
}
}
執行 cmdline2 John Paul Mary 將輸出:
Number of command line parameters = 3
John
Paul
Mary
args 是字串陣列,foreach 依序取出每個元素指派給變數 s,程式碼更簡潔易讀。
args.Length 取得參數總數。for 迴圈配合索引可同時存取索引與值。foreach 適合僅需順序讀取元素值的情境,語法更直觀。