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

Консольный ввод и вывод

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

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

Метод WriteLine очень полезен и часто используется при создании консольных приложений.

Метод WriteLine может отображать строки.

Console.WriteLine("Hello World!");

Метод WriteLine может также отображать числа.

int x = 42;

Console.WriteLine(x);

Если необходимо отобразить несколько элементов, используйте {0} для представления первого элемента, {1} — для второго элемента и так далее, следующим образом.

int year = 1066;

string battle = "Battle of Hastings";

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

Результат будет выглядеть следующим образом. 35

The Battle of Hastings took place in 1066.

Program Structure and Flow of Execution

When you create a C# application, you have the choice of creating a Console application or a Windows Forms application. The two differ not only in the type of user interface; they can also differ in their execution flow.

Windows Forms Applications

In a typical Windows-based application that has a graphical user interface, most of the action after initial startup occurs in response to user actions such as moving the mouse, selecting a menu option, or typing text. Such actions trigger events and special methods in your application named event handlers are called. Almost everything a Windows-based program does is initiated by an event handler. When no events are being generated, the program does nothing.

If you are used to procedural programming languages, such as COBOL, BASIC, or FORTRAN, you will have to get used to the event-driven model. The most fundamental difference is that, in event-driven programming, other software, and the operating system itself, is calling event-handler methods in your application. You do not know which methods they will call. You can decide which events to handle in your application, but you cannot know in advance the exact order in which those events will occur.

In a typical Windows-based application, fields, arrays, and collections that hold the application's state are put in the main Form class that is named Form1 by default. At the scope of the class, these members are accessible from all the event handler methods that are implemented in the same Form class. When an event handler is called, it may do something to modify the application data, and when the method returns, the application resumes its waiting state. For example, a form may contain a TextBox control and an Update button. When a user clicks the button, the application's event handler might get the text in the TextBox, for example, and then add it to a list of other strings that are stored at the scope of the class. After the string has been added, the application returns to the waiting state. Other event handlers may perform other kinds of actions on that same list of strings in response to user input.

Your own custom classes can send and receive events by using the same mechanisms as Windows Forms.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]