- •Введение в язык c# и .Net Framework
- •Язык c#
- •Архитектура платформы .Net Framework
- •Creating Your First c# Application
- •To create a c# application
- •Создание первого приложенияC#
- •Создание приложения c#
- •To create a c# console application
- •Создание консольного приложения c#
- •To create a c# Windows application
- •Создание приложений Windows Forms на c#
- •Introduction to Windows Presentation Foundation
- •To create a wpf application
- •Создание приложения wpf c#
- •To create event handlers
- •Создание обработчиков событий
- •Designing a User Interface in Visual c#
- •Adding Controls
- •Создание пользовательского интерфейса в Visual c#
- •Добавление элементов управления
- •Setting Properties
- •Handling Events
- •Задание свойств
- •Обработка событий
- •How to: Use Button Controls
- •Использование элемента управления "Button"
- •To use buttons in a program
- •Использование кнопок в программе
- •How to: Call a Button's Click Event Programmatically
- •To use buttons in a program
- •Программный вызов события нажатия кнопки
- •Использование кнопок в программе
- •How to: Create a Group of Radio Buttons from a String Array
- •Compiling the Code
- •Example
- •Создание группы переключателей из массива строк
- •Создание непрямоугольной кнопки
- •Компиляция кода
- •How to: Display Text on a Windows Form
- •To display text in a label
- •Отображение текста в форме Windows Forms
- •Отображение текста в надписи
- •How to: Use TextBox Controls to Get User Input
- •Использование элемента управления "TextBox" для получения вводимых данных
- •To retrieve input typed in a text box
- •Извлечение введенных в текстовое поле данных
- •How to: Convert the Text in a TextBox Control to an Integer
- •Диалоговые окна Извлечение данных из диалогового окна
- •To create the main form of your application
- •To create a dialog box
- •Создание основной формы приложения
- •Создание диалогового окна
- •Retrieving Data from a Dialog Box
- •To retrieve data from a dialog box.
- •Извлечение данных из диалогового окна
- •How to: Browse a Folder
- •To display the folder browser dialog box
- •Просмотр папки
- •Отображение диалогового окна обозревателя папок
- •How to: Save a File to a Folder
- •To display the folder browser dialog box
- •Сохранение файла в папку
- •Отображение диалогового окна обозревателя папок
- •How to: Display a List of Fonts
- •To display the font dialog box
- •Отображение списка шрифтов
- •Отображение диалогового окна выбора шрифта
- •How to: Display an OpenFileDialog Dynamically
- •Отображение цветовой палитры
- •Отображение диалогового окно выбора цвета
- •ListBox and ComboBox Controls
- •Compiling the Code
- •Отображение даты и времени в приложении
- •Отображение даты с помощью элемента управления "MonthCalendar"
- •To display the time by using a DateTimePicker control
- •Отображение времени с помощью элемента управления "DateTimePicker"
- •How to: Determine the Span Between Two Dates
- •Создание настраиваемого пользовательского интерфейса
- •Добавление панелей инструментов в приложение Windows Forms
- •To add a set of standard toolbar button
- •Добавление набора стандартных кнопок панели инструментов
- •How to: Create a Tooltip for a Control
- •Compiling the Code
- •Compiling the Code
- •Добавление элементов управления Windows Forms во время выполнения
- •Компиляция кода15
- •Accessing and Displaying Data
- •How to: Write Class Data to an xml File
- •Example
- •Compiling the Code
- •Compiling the Code
- •Robust Programming
- •Чтение xml из файла
- •Пример18
- •Компиляция кода
- •Надежное программирование
- •How to: Read Class Data from an xml File
- •Example
- •Compiling the Code
- •Robust Programming
- •Чтение данных класса из xml-файла
- •Пример19
- •Компиляция кода
- •Compiling the Code
- •Компиляция кода
- •Compiling the Code
- •Robust Programming
- •Рисование кривой в форме
- •Компиляция кода
- •Надежное программирование
- •How to: Draw Outlined Shapes
- •Example
- •Compiling the Code
- •Robust Programming
- •Рисование контурных фигур
- •Пример23
- •Компиляция кода
- •Добавление файлов мультимедиа в приложение
- •Внедрение проигрывателя Windows Media в форму
- •Добавление элемента управления "Windows Media Player" в панель элементов.
- •To add the Windows Media Player control to a Windows Form
- •Добавление элемента управления "Windows Media Player" в форму Windows Forms
- •How to: Play Sounds in an Application
- •To play an audio file
- •Воспроизведение звука в приложении
- •Воспроизведение аудиофайла
- •Creating and Using Bitmaps and Icons
- •How to: Create a Bitmap at Run Time
- •Example
- •Создание и использование точечных рисунков и значков
- •Создание точечного рисунка во время выполнения
- •Compiling the Code
- •Compiling the Code
- •Создание приложений wpf
- •Создание пользовательского интерфейса для приложения wpf
- •To create a wpf application
- •Создание приложения wpf
- •Adding Controls to the wpf Window You can add controls to the wpf window by dragging them from the Toolbox. To add a control to the wpf window
- •Добавление элементов управления в окно wpf
- •Добавление элемента управления в окно wpf
- •Common wpf Controls
- •Procedure To add a control to the wpf window
- •Стандартные элементы управления wpf
- •Процедура Добавление элемента управления в окно wpf
- •Standard wpf Controls
- •Стандартные элементы управления wpf
- •How to: Create Event Handlers for wpf Controls
- •To create an event handler for a button
- •Создание обработчиков событий для элементов управления wpf
- •Создание обработчика событий для кнопки
- •Connecting to Data
- •How to: Connect to a Database
- •To add a connection to the Northwind database
- •Подключение к данным
- •Подключение к базе данных
- •Добавление подключения к базе данных "Northwind"
- •How to: Display Related Data on a Form
- •To display related data on a form
- •Отображение связанных данных в форме
- •Отображение связанных данных в форме
- •Using linq in c# Express
- •Advantages of Using linq
- •Использование linq в c# Express
- •Преимущества использования linq
- •C# Language Enhancements that Support linq
- •Расширения языка c# для поддержки linq
- •Writing linq Queries
- •Linq to Objects
- •Написание запросов linq
- •Linq to Objects
- •Linq to sql
- •Linq to DataSet
- •Linq to xml
- •Linq to sql
- •Linq to DataSet
- •ЯзыкC# для начинающих Структура программы c#
- •"Hello World" в стиле c#
- •Using Directives and Namespaces
- •Comments
- •Директивыusingи пространства имен
- •Примечания
- •Classes
- •Console Input and Output
- •Консольный ввод и вывод
- •Program Structure and Flow of Execution
- •Windows Forms Applications
- •Структура программы и ход выполнения
- •Приложения Windows Forms
- •Console Applications
- •Namespaces
- •Консольные приложения
- •Пространства имен
- •Namespace Shortcuts
- •Creating Your Own Namespace
- •Ускоренные методы для пространства имен
- •Создание собственного пространства имен
- •Example
- •Classes
- •Classes vs. Objects
- •Классы и объекты
- •Static vs. Instance Members
- •Classes vs. Files
- •Члены экземпляра и статические члены
- •Классы и файлы
- •Encapsulation
- •Инкапсуляция
- •Inheritance
- •Polymorphism
- •Наследование
- •Полиморфизм
- •Constructors
- •Конструкторы
- •Operator Overloading
- •Compiling the Code
- •Имитация параметров по умолчанию
- •Компиляция кода
- •Structs
- •Example
- •Переменные и константы
- •Constants
- •Built-in Data Types
- •Константы
- •Встроенные типы данных
- •Using Built-in Data Types
- •Типы значений и ссылочные типы
- •Boxing and Unboxing
- •Упаковка и распаковка
- •Performance issues
- •Проблемы производительности
- •Operators
- •Decisions and Branching
- •Remarks
- •Выбор и ветвление
- •Foreach Loops
- •Циклы foreach
- •For Loops
- •Working with Strings
- •Доступ к отдельным знакам
- •Changing Case
- •Смена регистра
- •Comparisons
- •Сравнения
- •Splitting a String into Substrings
- •Разделение строки на подстроки
- •Using StringBuilder
- •Использование класса StringBuilder
- •How to: Generate Multiline String Literals
- •Массивы и коллекции
- •Массивы
- •Одномерные массивы
- •Multidimensional Arrays
- •Jagged Arrays
- •Многомерные массивы
- •Массивы массивов
- •Using the foreach Statement
- •Использование оператора foreach
- •Arrays of Objects
- •Массивы объектов
- •How to: Declare an Array
- •Compiling the Code
- •Robust Programming
- •Инициализация массива
- •Компиляция кода
- •Коллекции
- •How to: Iterate Through an Array
- •Compiling the Code
- •Компиляция кода
- •Enumerations
- •Перечисления
- •More Advanced Enumeration Techniques
- •Try and Catch
- •Обработка ошибок и исключений
- •Try и Catch
- •Finally Blocks
- •Using Exception Handling
- •You can also cause your own exceptions using the throw keyword.
- •Блоки finally
- •How to: Catch an Exception
- •Example
- •Compiling the Code
- •Перехват исключения
- •Program execution continues here...Компиляция кода
- •.Net Framework Conceptual Overview
- •Общие сведения об основных понятиях платформы .Net Framework
- •Features of the Common Language Runtime
- •Возможности среды clr
- •.Net Framework Class Library
- •Библиотека классов платформы .Net Framework
Консольный ввод и вывод
Программы
консоли на 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.