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

static int Main(string[] args)

static void Main(string[] args)


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)
{
return 1;
}


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


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


long num = Convert.ToInt64(s);


## 範例Example

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)
{
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)
{
Console.WriteLine("Usage: Factorial <num>");
return 1;
}

// Calculate factorial.
long result = Functions.Factorial(num);

// Print result.
if (result == -1)
Console.WriteLine("Input must be >= 0 and <= 20.");
else
Console.WriteLine(\$"The Factorial of {num} is {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

如果您的應用程式沒有任何編譯錯誤，則會建立名為階乘的可執行檔。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.