Компиляция кода
Скопируйте класс и вставьте его поверх Class1
в консольном приложении.40
How to: Declare a Property
This example declares an instance property.
Example
private string name;
// A read-write instance property:
public string NameProperty
{
get
{
return name;
}
set
{
name = value;
}
}
Compiling the Code
The code must appear within a class or a struct.
Robust Programming
You can use the get accessor to either return the field value or compute the value and return it, as follows:
get { return (name != null) ? name : "NA"; } |
Do not use the get accessor to change the state of the object, as follows: get { return myNumericField++; } |
Объявление свойства
В этом примере объявляется свойство экземпляра.
Пример
---------
Компиляция кода
Код должен появиться в классе или структуре.
Надежное программирование
Метод доступа get можно использовать для возвращения значения поля или для вычисления и возвращения этого значения, как показано в следующем примере.
get { return (name != null) ? name : "NA"; } |
Для изменения состояния объекта метод доступа get использовать нельзя.41 get { return myNumericField++; } |
How to: Set a Property on an Object
This example sets the CurrentDirectory
property on the Environment
class to C:\Public
.
Example
Environment.CurrentDirectory = "C:\\Public"; |
-or-
Environment.CurrentDirectory = @"C:\Public"; |
Compiling the Code
Copy the code, and paste it into the Main method of a console application.
Robust Programming
Use the fully qualified name of the property, unless it is accessible from the same scope.
Unless the property is static, it must be referenced through an instance of the class.
When assigning an expression to a property, make sure of the following:
That it is of a compatible data type.
That it has a valid value, especially if the value is derived from user input.
If you want more control over possible exceptions, enclose the property assignment in a try-catch statement.
Задание свойства объекта
В этом примере свойству CurrentDirectory
в классе Environment
задается значение C:\Public
.
Пример
Environment.CurrentDirectory = "C:\\Public"; |
или
Environment.CurrentDirectory = @"C:\Public"; |
Компиляция кода
Скопируйте код и вставьте его в метод Main консольного приложения.
Structs
A struct in C# is similar to a class, but structs lack certain features, such as inheritance. Also, since a struct is a value type, it can typically be created faster than a class. If you have tight loops in which new data structures are being created in large numbers, you should consider using a struct instead of a class. Structs are also used to encapsulate groups of data fields such as the coordinates of a point on a grid, or the dimensions of a rectangle.
Example
This example program defines a struct to store a geographic location. It also overrides the ToString() method to produce a more useful output when displayed in the WriteLine statement. As there are no methods in the struct, there is no advantage in defining it as a class.
struct GeographicLocation { private double longitude; private double latitude;
public GeographicLocation(double longitude, double latitude) { this.longitude = longitude; this.latitude = latitude; } public override string ToString() { return System.String.Format("Longitude: {0} degrees, Latitude: {1} degrees", longitude, latitude); } } class Program { static void Main() { GeographicLocation Seattle = new GeographicLocation(123, 47); System.Console.WriteLine("Position: {0}", Seattle.ToString()); } } |
Output
The output from this example looks like this:
Position: Longitude: 123 degrees, Latitude: 47 degrees
Структуры
Структура в C# аналогична классу, однако в структурах отсутствуют некоторые возможности, например наследование. Кроме того, поскольку структура является типом значения, ее можно создать быстрее, чем класс. При наличии непрерывного цикла, где создается большое количество новых структур данных, вместо класса рекомендуется использовать структуру. Структуры используются для инкапсуляции групп полей данных, таких как координаты точки в сетке или размеры прямоугольника.
Пример
В следующем примере программы определяется struct для сохранения географического расположения. Здесь также переопределяется метод ToString() для вывода более необходимых результатов при отображении в операторе WriteLine. Поскольку в struct методы отсутствуют, определение структуры в качестве класса бессмысленно.42
-----
Результат
После выполнения примера выводится следующий результат.
Position: Longitude: 123 degrees, Latitude: 47 degrees
Variables and Constants
A variable represents a numeric or string value or an object of a class. The value that the variable stores may change, but the name stays the same. A variable is one type of field. The following code is a simple example of how to declare an integer variable, assign it a value, and then assign it a new value.
int x = 1; // x holds the value 1 x = 2; // now x holds the value 2 |
In C#, variables are declared with a specific data type and a label. If your programming background is in loosely typed languages such as JScript, you are used to using the same "var" type for all variables, but in C# you must specify whether your variable is an int, a float, a byte, a short, or any of the more than 20 different data types. The type specifies, among other things, the exact amount of memory that must be allocated to store the value when the application runs. The C# language enforces certain rules when converting a variable from one type to another.
int answer = 42; string greeting = "Hello, World!"; double bigNumber = 1e100; System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber); |
- Введение в язык 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 Forms36
- Console Applications
- Namespaces
- Консольные приложения
- Пространства имен
- Namespace Shortcuts
- Creating Your Own Namespace
- Ускоренный доступ к содержимому пространства имен
- Создание собственного пространства имен
- Example
- Classes
- Classes vs. Objects
- Классы и объекты
- Static vs. Instance Members
- Classes vs. Files
- Члены экземпляра и статические члены37
- Классы и файлы
- Encapsulation
- Инкапсуляция
- Inheritance
- Polymorphism
- Наследование
- Полиморфизм
- Constructors
- Конструкторы
- Operator Overloading
- Compiling the Code
- Имитация параметров по умолчанию
- Компиляция кода
- Переменные и константы
- 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
- Перехват исключения
- Компиляция кода
- .Net Framework Conceptual Overview
- Общие сведения об основных понятиях платформы .Net Framework
- Features of the Common Language Runtime
- Возможности среды clr
- .Net Framework Class Library
- Библиотека классов платформы .Net Framework