Книга: Fedora™ Unleashed, 2008 edition

Printing Out the Parameters

Printing Out the Parameters

We're going to expand your little program by having it print out all the parameters passed to it, one per line. In C#, this is — rather sickeningly — just one line of code. Add this just after the existing Console.WriteLine() line in your program:

foreach (string arg in args) Console.WriteLine(arg);

The foreach keyword is a special kind of loop designed to iterate over an array of finite size. The for array exists in C#, and lets you loop a certain number of times; the while array exists too, and lets you loop continuously until you tell it to break. But the foreach loop is designed to loop over arrays that have a specific number of values, but you don't know how many values that will be. You get each value as a variable of any type you want — the preceding code says string arg in args, which means "for each array element in args, give it to me as the variable arg of type string. Of course, args is already an array of strings, so no datatype conversion will actually take place here — but it could if you wanted to convert classes or do anything of the like.

After you have each individual argument, call WriteLine() to print it out. This works whether there's one argument or one hundred arguments — or even if there are no arguments at all (in which case the loop doesn't execute at all).

Оглавление книги


Генерация: 1.122. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз