Hello World – Создаем первую программу
Следующая консольная программа – это версия традиционной программы "Hello World!" на языке C#, которая выводит на экран строку Hello World!.
ß---
Давайте разберем важные части этой программы по порядку.
Комментарии
Первая строка содержит комментарий.
// A "Hello World!" program in C# |
Символы // преобразуют остальную часть строки в комментарий. Можно также написать комментарий к блоку текста, окружив его символами /* и */, например:
/* A "Hello World!" program in C#. This program displays the string "Hello World!" on the screen. */ |
The Main Method
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 previous "Hello World!" example, it resides in a class named Hello. Declare the Main method in one of the following ways:
· It can return void:
static void Main() { //... } |
· It can also return an int:
static int Main() { //... return 0; } |
· With both of the return types, it can take arguments:
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. Notice that, unlike C++, this array does not include the name of the executable (exe) file.
Метод 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.
Компиляция и выполнение
Для компиляции программы "Hello World!" можно создать проект в среде IDE Visual Studio или воспользоваться командной строкой. Используйте средство командной строки Visual Studio или вызовите vsvars32.bat, чтобы в пути в командной строке открыть средство Visual C#.
|
|
Компиляция программы из командной строки.
· С помощью любого текстового редактора создайте исходный файл и сохраните его с именем Hello.cs. Файл исходного кода C# имеет расширение .cs.
· Чтобы вызвать компилятор, введите следующую команду:
csc Hello.cs
Если программа не содержит ошибок компиляции, то компилятор создает файл Hello.exe.
· Чтобы запустить программу, введите следующую команду:
Hello
Дата добавления: 2019-03-09; просмотров: 228; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!