通過以下方式之一定義方法,可以將參數(shù)發(fā)送至 Main 方法。
static int Main(string[] args)
static void Main(string[] args)
【備注】若要在 Windows 窗體應(yīng)用程序中的 Main 方法中啟用命令行參數(shù),必須手動修改 program.cs 中 Main 的簽名。 Windows 窗體設(shè)計器生成的代碼創(chuàng)建沒有輸入?yún)?shù)的 Main。 也可以使 用 Environment.CommandLine 或 Environment.GetCommandLineArgs 從控制臺或 Windows 應(yīng)用程序中的任何位置訪問命令行參數(shù)。
Main 方法的參數(shù)是表示命令行參數(shù)的 String 數(shù)組。 一般是通過測試 Length 屬性來確定參數(shù)是否存在,例如:
if (args.Length == 0) { WriteLine("Hello World."); return 1; }
還可以使用 Convert 類或 Parse 方法將字符串參數(shù)轉(zhuǎn)換為數(shù)值類型。 例如,下面的語句使用 Parse 方法將 string 轉(zhuǎn)換為 long 數(shù)字:
long num = Int64.Parse(args[0]);
也可以使用別名為 Int64 的 C# 類型 long:
long num = long.Parse(args[0]);
還可以使用 Convert 類的方法 ToInt64 完成同樣的工作:
long num = Convert.ToInt64(s);
示例
下面的示例演示如何在控制臺應(yīng)用程序中使用命令行參數(shù)。 應(yīng)用程序在運行時采用一個參數(shù),將該參數(shù)轉(zhuǎn)換為整數(shù),并計算該數(shù)的階乘。 如果沒有提供參數(shù),則應(yīng)用程序發(fā)出一條消息來解釋程序的正確用法。
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; } }
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網(wǎng)!
新聞熱點
疑難解答
圖片精選