Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Учебник_ПОА.doc
Скачиваний:
92
Добавлен:
13.02.2015
Размер:
2.65 Mб
Скачать

Комментарий

Следующая после оператора using строка содержит комментарий. Комментарии являются полезными для включения в них примечаний для себя или других программистов.

// A Hello World! program in C#

Символы // преобразуют остальную часть строки в комментарий. Можно также закомментировать блок текста, поместив его между символами /* и */, как в примере.

/* A "Hello World!" program in C#.

This program displays the string "Hello World!" on the screen. */

Classes

The C# language uses classes to package code: all executable C# code must be contained in a class.

Main()

  • The C# program must contain a Main method, in which control starts and ends. The Main method is where you create objects and execute other methods. The Main method is a static method that resides inside a class or a struct. In the "Hello World!" example, it resides inside the Program class.

The Main method can be defined in one of the following ways:

  • It can return void:

    static void Main()

    {

    //...

    }

  • It can also return an int:

    static int Main()

    {

    //...

    return 0;

    }

  • It can take arguments, which are useful for command line utilities:

    static void Main(string[] args)

    {

    //...

    }

  • -or-

static int Main(string[] args)

{

//...

return 0;

}

The parameter of the Main method is a string array that represents the command-line arguments used to invoke the program.

Классы

В C# классы используются для оформления кода: весь выполняемый код C# должен содержаться в классе

Main()

  • В программе на C# должен присутствовать метод Main, в котором начинается и заканчивается управление. В методе Main создаются объекты и выполняются другие методы. Метод Main является статическим методом, расположенным внутри класса или структуры. В предыдущем примере "Hello World!" он расположен в классе с именем Program.

Метод Main можно объявить одним из следующих способов:

  • Он возвращает значение void.

static void Main()

{

//...

}

  • Он также может возвращать значение типа int.

static int Main()

{

//...

return 0;

}

  • Он может принимать аргументы, что может быть полезно для программ, использующих информацию командной строки.

static void Main(string[] args)

{

//...

}

или

static int Main(string[] args)

{

//...

return 0;

}

Параметр метода Main является массивом значений типа string, представляющим аргументы командной строки, используемые при вызове программы.

Console Input and Output

C# console programs generally use the input/output services provided by .NET Framework Console class. The statement Console.WriteLine("Hello, World!"); uses the WriteLine method. It displays its string parameter on the command-line window followed by a new line. Other Console methods are used for different input and output operations. The Console class is a member of the System namespace. If the using System; statement was not included at the beginning of the program, you would have to specify the System classes like this:

System.Console.WriteLine("Hello World!");

The WriteLine method is very useful, and you will use it a lot if you are writing console applications.

WriteLine can display strings:

Console.WriteLine("Hello World!");

WriteLine can also display numbers:

int x = 42;

Console.WriteLine(x);

If you need to display several items, use {0} to represent the first item, {1} the second item, and so on, like this:

int year = 1066;

string battle = "Battle of Hastings";

Console.WriteLine("The {0} took place in {1}.", battle, year);

The output will look like this:

The Battle of Hastings took place in 1066.