How to: Display Command Line Arguments 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

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]

Отображение аргументов командной строки

Для доступа к аргументам, предоставленным для исполняемого файла в командной строке, можно использовать необязательный параметр для Main. Аргументы представлены в форме массива или строк. Каждый элемент массива содержит один аргумент. Пробел между элементами удален. Например, рассмотрим следующие вызовы вымышленного исполняемого файла из командной строки.

Данные, вводимые в командную строку Массив строк, переданный в Main
исполняемый файл.exe a b c "a" "b" "c"
исполняемый файл.exe один два "один" "два"
исполняемый файл.exe "один два" три "один два" "три"

Пример

В этом примере показаны аргументы командной строки, переданные в приложение командной строки. Далее представлен результат для первой записи в расположенной выше таблице.

ß--


How to: Access Command-Line Arguments Using foreach

Another approach to iterating over the array is to use the foreach statement as shown in this example. The foreach statement can be used to iterate over an array, a.NET Framework collection class, or any class or struct that implements the IEnumerable interface.

Example

This example demonstrates how to print out the command line arguments using foreach.

// arguments: John Paul Mary  
class CommandLine2 { static void Main(string[] args) { System.Console.WriteLine("Number of command line parameters = {0}", args.Length);   foreach (string s in args) { System.Console.WriteLine(s); } } }  

 

Number of command line parameters = 3 John Paul Mary

 


Доступ к аргументам командной строки с помощью оператора "foreach"

Другим методом итерации всех элементов массива является использование оператора foreach, как показано в следующем примере. Оператор foreach можно использовать для итерации всех элементов массива, класса коллекции.NET Framework или любого класса или структуры, реализующих интерфейс IEnumerable.

Пример

В данном примере показано, как напечатать аргументы командной строки с помощью оператора foreach.

ß--


Main() Return Values

The Main method can be of the type void:

static void Main() { //... }  

It can also return an int:

static int Main() { //... return 0; }  

If the return value from Main is not to be used, then returning void allows slightly simpler code. However, returning an integer enables the program to relate status information to other programs or scripts that invoke the executable. An example of using the return value from Main is shown in the following example.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 95; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.219.95.244 (0.003 с.)