Share via


命令列引數 (C# 程式設計手冊)

Main 方法可以使用引數,在這種狀況下,它會採用下列格式之一:

static int Main(string[] args)
static void Main(string[] args)
注意事項注意事項

若要啟用 Windows Form 應用程式之 Main 方法的命令列引數,您必須手動修改 program.cs 中 Main 的簽章。 Windows Form 設計工具所產生的程式碼會建立一個不含輸入參數的 Main。 您也可以使用 Environment.CommandLineEnvironment.GetCommandLineArgs,從主控台或 Windows 應用程式中的任何點來存取命令列引數。

Main 方法的參數是代表命令列引數的 String 陣列。 通常您可以測試 Length 屬性來判斷引數是否存在,例如:

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

您也可以使用 Convert 類別或 Parse 方法將字串引數轉換成數字型別。 例如,下列陳述式會使用 Parse 方法,將 string 轉換成 long 值:

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

也可以使用 C# 型別的 long,這是 Int64 的別名:

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

您也可以使用 Convert 類別方法 ToInt64 來達成同樣的目的:

long num = Convert.ToInt64(s);

如需詳細資訊,請參閱 ParseConvert

範例

下列範例將示範如何在主控台應用程式中使用命令列引數。 程式會在執行階段使用一個引數、將該引數轉換成整數,並且計算該數字的階乘。 如果沒有提供引數,這個程式會發出一個解釋該程式正確用法的訊息。

注意事項注意事項

在 Visual Studio 中執行應用程式時,您可以在專案設計工具、偵錯頁中指定命令列引數。

如需如何使用命令列引數的其他範例,請參閱 HOW TO:使用命令列建立和使用組件 (C# 和 Visual Basic)

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.

請參閱

工作

HOW TO:顯示命令列引數 (C# 程式設計手冊)

HOW TO:使用 foreach 存取命令列引數 (C# 程式設計手冊)

參考

Main() 傳回值 (C# 程式設計手冊)

類別 (C# 程式設計手冊)

System.Environment

概念

C# 程式設計手冊

Main() 和命令列引數 (C# 程式設計手冊)