命令列引數 (C# 程式設計手冊)Command-Line Arguments (C# Programming Guide)

您可以使用下列其中一種方式,透過定義方法以將引數傳送給 Main 方法:You can send arguments to the Main method by defining the method in one of the following ways:

static int Main(string[] args)
static void Main(string[] args)

注意

若要在 Windows Forms 應用程式的 Main 方法中啟用命令列引數,您必須手動修改 program.cs 中 Main 的簽章。To enable command-line arguments in the Main method in a Windows Forms application, you must manually modify the signature of Main in program.cs. Windows Forms 設計工具所產生的程式碼會建立沒有輸入參數的 MainThe code generated by the Windows Forms designer creates a Main without an input parameter. 您也可以使用 Environment.CommandLineEnvironment.GetCommandLineArgs,以從主控台或 Windows 應用程式的任何點存取命令列引數。You can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows application.

Main 方法的參數是代表命令列引數的 String 陣列。The parameter of the Main method is a String array that represents the command-line arguments. 您通常會透過測試 Length 屬性來決定引數是否存在,例如:Usually you determine whether arguments exist by testing the Length property, for example:

if (args.Length == 0)
{
    System.Console.WriteLine("Please enter a numeric argument.");
    return 1;
}

您也可以使用 Convert 類別或 Parse 方法,將字串引數轉換為數字類型。You can also convert the string arguments to numeric types by using the Convert class or the Parse method. 例如,下列陳述式將使用 Parse 方法,以將 string 轉換為 long 數字:For example, the following statement converts the string to a long number by using the Parse method:

long num = Int64.Parse(args[0]);  

也可能使用別名為 Int64 的 C# 類型 longIt is also possible to use the C# type long, which aliases Int64:

long num = long.Parse(args[0]);  

您還可以使用 Convert 類別方法 ToInt64 執行相同作業:You can also use the Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);  

如需詳細資訊,請參閱 ParseConvertFor more information, see Parse and Convert.

範例Example

下列範例示範如何在主控台應用程式中使用命令列引數。The following example shows how to use command-line arguments in a console application. 應用程式會在執行階段接受一個引數,並將引數轉換為整數,以及計算數字的階乘。The application takes one argument at run time, converts the argument to an integer, and calculates the factorial of the number. 如果未提供任何引數,則應用程式會發出說明程式正確用法的訊息。If no arguments are supplied, the application issues a message that explains the correct usage of the program.

若要從命令提示字元編譯和執行應用程式,請遵循下列步驟︰To compile and run the application from a command prompt, follow these steps:

  1. 將下列程式碼貼入任何文字編輯器,然後將檔案儲存為名稱為 Factorial.cs 的文字檔案。Paste the following code into any text editor, and then save the file as a text file with the name Factorial.cs.

    //Add a using directive for System if the directive isn't already present.
    
    public class Functions
    {
        public static long Factorial(int n)
        {
            // Test for invalid input
            if ((n < 0) || (n > 20))
            {
                return -1;
            }
    
            // Calculate the factorial iteratively rather than recursively:
            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)
            {
                System.Console.WriteLine("Please enter a numeric argument.");
                System.Console.WriteLine("Usage: Factorial <num>");
                return 1;
            }
    
            // Try to convert the input arguments to numbers. This will throw
            // an exception if the argument is not a number.
            // num = int.Parse(args[0]);
            int num;
            bool test = int.TryParse(args[0], out num);
            if (test == false)
            {
                System.Console.WriteLine("Please enter a numeric argument.");
                System.Console.WriteLine("Usage: Factorial <num>");
                return 1;
            }
    
            // Calculate factorial.
            long result = Functions.Factorial(num);
    
            // Print result.
            if (result == -1)
                System.Console.WriteLine("Input must be >= 0 and <= 20.");
            else
                System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
    
            return 0;
        }
    }
    // If 3 is entered on command line, the
    // output reads: The factorial of 3 is 6.
    
  2. 從 [開始] 畫面或 [開始] 功能表中,開啟 Visual Studio [開發人員命令提示字元] 視窗,然後巡覽至包含剛剛建立之檔案的資料夾。From the Start screen or Start menu, open a Visual Studio Developer Command Prompt window, and then navigate to the folder that contains the file that you just created.

  3. 輸入下列命令以編譯應用程式。Enter the following command to compile the application.

    csc Factorial.cs

    如果您的應用程式沒有任何編譯錯誤,則會建立名為 Factorial.exe 的可執行檔。If your application has no compilation errors, an executable file that's named Factorial.exe is created.

  4. 輸入下列命令以計算 3 的階乘:Enter the following command to calculate the factorial of 3:

    Factorial 3

  5. 命令會產生以下輸出:The factorial of 3 is 6.The command produces this output: The factorial of 3 is 6.

注意

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

如需如何使用命令列引數的其他範例,請參閱如何:使用命令列建立和使用組件For more examples about how to use command-line arguments, see How to: Create and Use Assemblies Using the Command Line.

另請參閱See Also

System.Environment
C# 程式設計指南C# Programming Guide
Main() 和命令列引數Main() and Command-Line Arguments
如何:顯示命令列引數How to: Display Command Line Arguments
如何:使用 foreach 存取命令列引數How to: Access Command-Line Arguments Using foreach
Main() 傳回值Main() Return Values
類別Classes