Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Main() и аргументы командной строки

Метод Main является точкой входа программы, где создаются объекты и вызываются другие методы. В программе C# возможна только одна точка входа.

class TestClass

{

static void Main(string[] args)

{

// Display the number of command line arguments:

System.Console.WriteLine(args.Length);

}

}

Общие сведения

  • Метод Main является точкой входа программы, в которой начинается и заканчивается управление программой.

  • Он объявляется внутри класса или структуры. Он должен быть статическим и не должен быть общим. (В приведенном выше примере он получает доступ по умолчанию типа “закрытый”.)

  • Он может иметь возвращаемый тип void или int.

  • Метод Main может быть объявлен с параметрами или без них.

  • Параметры считываются как аргументы командной строки с нулевым индексированием.

  • В отличие от языков C и C++, имя программы не рассматривается в качестве первого аргумента командной строки.

Command-Line Arguments

The Main method can use arguments, in which case, it takes one of the following forms:

static int Main(string[] args)

static void Main(string[] args)

The parameter of the Main method is a String array that represents the command-line arguments. Usually you check for the existence of the arguments by testing the Length property, for example:

if (args.Length == 0)

{

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

return 1;

}

You can also convert the string arguments to numeric types by using the Convert class or the Parse method. For example, the following statement converts the string to a long number by using the Parse method on the Int64 class:

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

It is also possible to use the C# type long, which aliases Int64:

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

You can also use the Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);

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

Метод 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]