logo
CSharp_Prog_Guide

Аргументы командной строки

Метод Main может использовать аргументы, принимая в этом случае одну из следующих форм:

static int Main(string[] args)

static void Main(string[] args)

Параметр метода Main является массивом значений типа String, представляющим аргументы командной строки. Обычно наличие аргументов проверяется путем проверки свойства Length, например:

if (args.Length == 0)

{

System.Console.WriteLine("Please enter a numeric argument.");

return 1;

}

Кроме того, строковые аргументы можно преобразовать в числовые типы с помощью класса Convert или метода Parse. Например, следующая инструкция преобразует строку в число типа long с помощью метода Parse класса Int64:

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

Также можно использовать тип long языка C#, являющийся псевдонимом типа Int64:

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

Для выполнения этой операции также можно воспользоваться методом ToInt64 класса Convert:

long num = Convert.ToInt64(s);

Example

In this example, the program 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 program issues a message that explains the correct usage of the program.

// arguments: 3

public class Functions

{

public static long Factorial(int n)

{

if (n < 0) { return -1; } //error result - undefined

if (n > 256) { return -2; } //error result - input is too big

if (n == 0) { 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

{

// Convert the input arguments to numbers:

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

System.Console.WriteLine("The Factorial of {0} is {1}.", num, Functions.Factorial(num));

return 0;

}

catch (System.FormatException)

{

System.Console.WriteLine("Please enter a numeric argument.");

System.Console.WriteLine("Usage: Factorial <num>");

return 1;

}

}

}

Пример

В этом примере программа принимает аргументы по одному и преобразует каждый из них в целое и вычисляет факториал этого числа. Если ни одного аргумента не предоставлено, то программа выдает сообщение, содержащее разъяснение правильного использования данной программы.

--------------

Output

The Factorial of 3 is 6.

Comments

The following are two sample runs of the program assuming that the program name is Factorial.exe.

Run #1:

Enter the following command line:

Factorial 10

You get the following result:

The Factorial of 10 is 3628800.

Run #2:

Enter the following command line:

Factorial

You get the following result:

Please enter a numeric argument.

Usage: Factorial <num>

Результат

The Factorial of 3 is 6.

Примечания

Ниже приведены два примера выполнения программы, имя файла которой Factorial.exe.

Выполнение №1.

Введите следующую командную строку:

Factorial 10

Результат будет следующим:

The Factorial of 10 is 3628800.

Выполнение №2.

Введите следующую командную строку:

Factorial

Результат будет следующим:

Please enter a numeric argument.

Usage: Factorial <num>

How to: Display Command Line Arguments

Arguments provided to an executable on the command-line are accessible through an optional parameter to Main. The arguments are provided in the form of an array of strings. Each element of the array contains one argument. White-space between arguments is removed. For example, consider these command-line invocations of a fictitious executable:

Input on Command-line

Array of strings passed to Main

executable.exe a b c

"a"

"b"

"c"

executable.exe one two

"one"

"two"

executable.exe “one two” three

"one two"

"three"

Example

This example displays the command line arguments passed to a command-line application. The output shown is for the first entry in the table above.

class CommandLine

{

static void Main(string[] args)

{

// The Length property provides the number of array elements

System.Console.WriteLine("parameter count = {0}", args.Length);

for (int i = 0; i < args.Length; i++)

{

System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);

}

}

}

parameter count = 3

Arg[0] = [a]

Arg[1] = [b]

Arg[2] = [c]