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

Метод Main

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

Метод Main является статическим методом, расположенным внутри класса или структуры. В предыдущем примере "Hello World!" он расположен в классе с именем Hello. Метод 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, представляющим аргументы командной строки, используемые для вызова программы. Обратите внимание, что в отличие от C++, массив не содержит исполняемого (EXE) файла.

Input and Output

C# programs generally use the input/output services provided by the run-time library of the .NET Framework. The statement, System.Console.WriteLine("Hello World!"); uses the WriteLine method, one of the output methods of the Console class in the run-time library. It displays its string parameter on the standard output stream followed by a new line. Other Console methods are used for different input and output operations. If you include the using System; directive at the beginning of the program, you can directly use the System classes and methods without fully qualifying them. For example, you can call Console.WriteLine instead, without specifying System.Console.Writeline:

using System;

Console.WriteLine("Hello World!");

For more information about input/output methods, see System.IO.

Compilation and Execution

You can compile the "Hello World!" program either by creating a project in the Visual Studio IDE, or by using the command line. Use the Visual Studio Command Prompt or invoke vsvars32.bat to put the Visual C# tool set on the path in your command prompt.

To compile the program from the command line:

  • Create the source file by using any text editor and save it using a name such as Hello.cs. C# source code files use the extension .cs.

  • To invoke the compiler, enter the command:

csc Hello.cs

If your program does not contain any compilation errors, a Hello.exe file will be created.

  • To run the program, enter the command:

Hello

Ввод и вывод

Программы на C#, как правило, используют службы ввода/вывода, предоставляемые библиотекой времени выполнения в .NET Framework. Оператор System.Console.WriteLine("Hello World!"); использует WriteLine – один из методов вывода класса Console в библиотеке времени выполнения. Он выводит свои строковые параметры в стандартном потоке вывода, за которым следует новая строка. Другие методы Console используются для разных операций ввода и вывода. Если в начало программы поместить директиву using System;, классы System и методы можно будет использовать напрямую без указания их полного имени. Например, можно вызвать Console.WriteLine без указания System.Console.Writeline:

using System;

Console.WriteLine("Hello World!");

Дополнительные сведения о методах ввода/вывода см. в разделе System.IO.