通過以下方式之一定義方法,可以將參數發送至 Main 方法。
static int Main(string[] args)
static void Main(string[] args)
【備注】若要在 Windows 窗體應用程序中的 Main 方法中啟用命令行參數,必須手動修改 program.cs 中 Main 的簽名。 Windows 窗體設計器生成的代碼創建沒有輸入參數的 Main。 也可以使 用 Environment.CommandLine 或 Environment.GetCommandLineArgs 從控制台或 Windows 應用程序中的任何位置訪問命令行參數。
Main 方法的參數是表示命令行參數的 String 數組。 一般是通過測試 Length 屬性來確定參數是否存在,例如:
if (args.Length == 0)
{
WriteLine("Hello World.");
return 1;
}
還可以使用 Convert 類或 Parse 方法將字符串參數轉換為數值類型。 例如,下面的語句使用 Parse 方法將 string 轉換為 long 數字:
long num = Int64.Parse(args[0]);
也可以使用別名為 Int64 的 C# 類型 long:
long num = long.Parse(args[0]);
還可以使用 Convert 類的方法 ToInt64 完成同樣的工作:
long num = Convert.ToInt64(s);
下面的示例演示如何在控制台應用程序中使用命令行參數。 應用程序在運行時采用一個參數,將該參數轉換為整數,並計算該數的階乘。 如果沒有提供參數,則應用程序發出一條消息來解釋程序的正確用法。
public class Functions
{
public static long Factorial(int n)
{
if ((n < 0) || (n > 20))
{
return -1;
}
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
Console.WriteLine("Please enter a numeric argument.");
Console.WriteLine("Usage: Factorial <num>");
return 1;
}
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
Console.WriteLine("Please enter a numeric argument.");
Console.WriteLine("Usage: Factorial <num>");
return 1;
}
long result = Functions.Factorial(num);
if (result == -1)
Console.WriteLine("Input must be >= 0 and <= 20.");
else
Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}