Строки стандартных числовых форматов
Строки стандартных числовых форматов служат для форматирования стандартных числовых типов. Стандартная строка числового формата имеет вид Axx, где A является символом буквы, называемой спецификатором, а xx является опциональным целым числом, называемым спецификатором точности. Спецификатор точности находится в диапазоне от 0 до 99 и влияет на число цифр в результате. Любая строка числового формата, содержащая более одной буквы, включая пробелы, интерпретируется как строка пользовательского числового формата.
В следующей таблице описаны спецификаторы стандартных числовых форматов и отображены примеры выходных данных, производимых каждым спецификатором формата. Дополнительные сведения содержатся в разделе примечания, расположенном после таблицы.
Format specifier | Name | Description | |
C or c | Currency | The number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the current NumberFormatInfo object. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the current NumberFormatInfo object is used. The following example formats a Double value with the currency format specifier.
|
Описатель формата | Имя | Описание |
C или c | Валюта | Число преобразуется в строку, представляющую денежные единицы. Преобразование регулируется сведениями о форматировании денежных единиц текущего объекта NumberFormatInfo. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, используется значение по умолчанию объекта NumberFormatInfo. В следующем примере значение Double форматируется с помощью спецификатора денежного формата. |
------------
D or d | Decimal | This format is supported only for integral types. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. The following example formats an Int32 value with the Decimal format specifier.
|
D или d | Десятичное число | Этот формат доступен только для целых типов. Число преобразуется в строку, состоящую из десятичных цифр (0-9); если число отрицательное, перед ним ставится знак "минус". Минимальное количество знаков в выходной строке задается спецификатором точности. Недостающие знаки в строке заменяются нулями. В следующем примере значение Int32 форматируется с помощью спецификатора десятичного формата. |
---------
E or e | Scientific (exponential) | The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required. The following example formats a Double value with the scientific format specifier.
|
E или e | Научный (экспоненциальный) | Число преобразуется в строку вида "-d.ddd…E+ddd" или "-d.ddd…e+ddd”, где знак "d" представляет цифру (0-9). Если число отрицательное, в начале строки появляется знак "минус". Перед разделителем целой и дробной части всегда стоит один знак. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию число знаков дробной части равно шести. Регистр спецификатора формата задает регистр буквы, стоящей перед экспонентой ("E" или "e"). Экспонента состоит из знака "плюс" или "минус" и трех цифр. Недостающие до минимума цифры заменяются нулями, если это необходимо. В следующем примере значение Double форматируется с помощью спецификатора экспоненциального формата. |
---------------
F or f | Fixed-point | The number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision is given by the NumberDecimalDigits property of the current NumberFormatInfo object. The following example formats a Double and an Int32 value with the fixed-point format specifier.
|
F или f | Фиксированная запятая | Число преобразуется в строку вида "-ddd.ddd…", где знак "d" представляет цифру (0-9). Если число отрицательное, в начале строки появляется знак "минус". Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию точность числа задается свойством NumberDecimalDigits текущего объекта NumberFormatInfo. В следующем примере значение Double и значение Int32 форматируются с помощью спецификатора формата с фиксированной точкой. |
-------
G or g | General | The number is converted to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated by the following list.
Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. The result contains a decimal point if required and trailing zeroes are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, then the excess trailing digits are removed by rounding. The exception to the preceding rule is if the number is a Decimal and the precision specifier is omitted. In that case, fixed-point notation is always used and trailing zeroes are preserved. If scientific notation is used, the exponent in the result is prefixed with 'E' if the format specifier is 'G', or 'e' if the format specifier is 'g'. The following example formats assorted floating-point values with the general format specifier.
|
G или g | Общий | Число преобразуется в наиболее короткую запись из записи с фиксированной запятой или экспоненциальной записи, в зависимости от типа числа и наличия спецификатора точности. Если спецификатор точности не задан или равен нулю, точность задается типом переменной, как показано в следующем списке.
Нотация с фиксированной запятой используется, если экспонента результата в экспоненциальной нотации длиннее пяти знаков, но меньше спецификатора точности, в противном случае используется научная нотация. Результат содержит разделитель целой и дробной частей, последние нули дробной части отбрасываются. Если спецификатор точности задан и число значащих цифр результата превосходит его значение, лишние знаки отбрасываются округлением. Составляется исключение из предыдущего правила, если число имеет тип Decimal и не указан спецификатор точности. В этом случае используется нотация с фиксированной запятой, последние нули дробной части сохраняются. Если используется научная нотация, регистр буквы, стоящей перед экспонентой задается регистром указателя формата (буква "E" соответствует "G", "e" соответствует "g"). В следующем примере различные значения с плавающей запятой форматируются с помощью спецификатора общего формата. |
double number;
number = 12345.6789;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 12345.6789
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68
number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
double number;
number = 12345.6789;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 12345.6789
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68
number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
N or n | Number | The number is converted to a string of the form "-d,ddd,ddd.ddd…", where '-' indicates a negative number symbol if required, 'd' indicates a digit (0-9), ',' indicates a thousand separator between number groups, and '.' indicates a decimal point symbol. The actual negative number pattern, number group size, thousand separator, and decimal separator are specified by the NumberNegativePattern, NumberGroupSizes, NumberGroupSeparator, and NumberDecimalSeparator properties, respectively, of the current NumberFormatInfo object. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision is given by the NumberDecimalDigits property of the current NumberFormatInfo object. The following example formats assorted floating-point values with the number format specifier.
|
N или n | Число | Число преобразуется в строку вида "-d,ddd,ddd.ddd… “, где знак '-' при необходимости представляет знак "минус", знак "d" - цифра (0-9), знак "," - разделитель тысяч, а знак "" - разделитель целой и дробной части. Фактический шаблон отрицательного числа, размер групп числа, разделитель тысяч и десятичный разделитель задаются свойствами NumberNegativePattern, NumberGroupSizes, NumberGroupSeparator и свойством NumberDecimalSeparator, соответственно, текущего объекта NumberFormatInfo. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию точность числа задается свойством NumberDecimalDigits текущего объекта NumberFormatInfo. В следующем примере различные значения с плавающей запятой форматируются с помощью спецификатора числового формата. |
-----------
P or p | Percent | The number is converted to a string that represents a percent as defined by the NumberFormatInfo..::.PercentNegativePattern property if the number is negative, or the NumberFormatInfo..::.PercentPositivePattern property if the number is positive. The converted number is multiplied by 100 in order to be presented as a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the current NumberFormatInfo object is used. The following example formats floating-point values with the percent format specifier.
|
P или p | Процент | Число преобразуется в строку, представляющую проценты, как определено свойством NumberFormatInfo..::.PercentNegativePattern, если число отрицательно, или свойством NumberFormatInfo..::.PercentPositivePattern, если число положительно. Преобразуемое число умножается на 100, чтобы соответствовать процентам. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, то используется значение по умолчанию объекта NumberFormatInfo. В следующем примере значения с плавающей запятой форматируются с помощью спецификатора процентного формата. |
------------
R or r | Round-trip | This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although a precision specifier can be present, it is ignored. Round trips are given precedence over precision when using this specifier. The following example formats Double values with the round-trip format specifier.
|
R или r | Приемо-передача | Этот формат поддерживается только для типа Single и для типа Double. Этот спецификатор гарантирует, что отформатированное строковое значение будет разобрано в то же самое числовое значение. При форматировании числового значения с помощью этого спецификатора сначала производится форматирование в общий формат с 15 значащими цифрами для переменных типа Double и 7 значащими цифрами для переменных типа Single. Если анализ строки показывает, что представленная ей переменная приняла то же значение, форматирование производится с помощью общего указателя формата. Однако если анализ изменяет значение переменной, то количество значащих цифр увеличивается до 17 для типа Double и 9 значащих цифр для типа Single. Даже если спецификатор точности будет присутствовать, он будет проигнорирован. В следующем примере значения Double форматируются с помощью спецификатора формата приема-передачи. |
--------------
X or x | Hexadecimal | This format is supported only for integral types. The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce "ABCDEF", and 'x' to produce "abcdef". The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. The following example formats Int32 values with the hexadecimal format specifier.
|
X или x | Шестнадцатеричный | Этот формат доступен только для целых типов. Число преобразуется в строку шестнадцатеричных знаков. Регистр шестнадцатеричных знаков, превосходящих 9, совпадает с регистром указателя формата. Например, чтобы отображать эти цифры в виде "ABCDEF", задайте указатель "X"; и указатель "x", чтобы получить "abcdef". Минимальное количество знаков в выходной строке задается спецификатором точности. Недостающие знаки в строке заменяются нулями. В следующем примере значения Int32 форматируются с помощью спецификатора шестнадцатеричного формата. |
--------------
Notes
Control Panel Settings
The settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. Those settings are used to initialize the NumberFormatInfo object associated with the current thread culture, and the current thread culture provides values used to govern formatting. Computers using different settings will generate different result strings.
In addition, if the CultureInfo..::.CultureInfo(String) constructor is used to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. You can use the CultureInfo..::.CreateSpecificCulture method to create a CultureInfo that does not reflect a system's customizations.
NumberFormatInfo Properties
Formatting is influenced by properties of the current NumberFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. Specify a NumberFormatInfo or CultureInfo object for that parameter.
Integral and Floating-Point Numeric Types
Some descriptions of standard numeric format specifiers refer to integral or floating-point numeric types. The integral numeric types are Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, and UInt64. The floating-point numeric types are Decimal, Single, and Double.
Floating-Point Infinities and NaN
Note that regardless of the format string, if the value of a Single or Double floating-point type is positive infinity, negative infinity, or Not a Number (NaN), the formatted string is the value of the respective PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol property specified by the currently applicable NumberFormatInfo object.
- Оглавление
- Метод Main
- Ввод и вывод
- Компиляция и выполнение
- Общая структура программы на c#
- Main() и аргументы командной строки
- Общие сведения
- Аргументы командной строки
- Отображение аргументов командной строки
- Доступ к аргументам командной строки с помощью оператора "foreach"
- Значения, возвращаемые методом Main()
- Пример результатов выполнения
- Общие сведения о типах данных
- Приведение
- Результат
- Упаковка-преобразование и распаковка-преобразование3
- Производительность
- Упаковка-преобразование4
- Описание5
- Результат
- Распаковка-преобразование6
- Описание7
- Результат
- Преобразование массива байтов в значение типа "int"8
- Пример9
- Преобразование строки в значение типа "int"
- Преобразование шестнадцатеричных строк10
- Массивы
- Общие сведения о массивах
- Массивы как объекты
- Результат
- Одномерные массив
- Массивы типов значений и ссылочных типов.
- Многомерные массивы
- Инициализация массива
- Массивы массивов
- Результат
- Использование оператора foreach с массивами
- Передача массивов в качестве параметров
- Передача одномерных массивов в качестве параметров
- Пример 1 Описание
- Результат 1
- Передача многомерных массивов в качестве параметров
- Пример 2 Описание
- Передача массивов при помощи параметров ref и out
- Пример 1
- Пример 2
- Неявно типизированные массивы11
- Неявно типизированные массивы в инициализаторах объектов12
- Использование строк
- Работа со строками Escape-знаки
- Точные строки: символ @
- Доступ к отдельным знакам
- Смена регистра
- Сравнения
- Разделение строки на подстроки
- Строки с нулевыми значениями и пустые строки
- Использование класса StringBuilder13
- Анализ строк с помощью метода разделения
- Навигация по содержимому строки с помощью строковых методов
- Анализ строк с помощью регулярных выражений14
- Объединение нескольких строк
- Изменение содержимого строки
- Определение наличия числового значения в строке
- Надежное программирование
- Безопасность
- Базовые типы кодировки
- Типы форматирования
- Общие сведения о форматировании
- Описатели формата
- Анализ и описатели формата
- Метод ToString и описатели формата
- Поставщики формата15
- Составное форматирование
- Форматирование базовых типов
- Форматирование для различных языков и региональных параметров16
- Составное форматирование
- Строка составного формата
- Синтаксис элементов форматирования
- Выравнивание
- Компонент строки формата
- Оформление фигурных скобок17
- Порядок обработки18
- Примеры кода
- Строки числовых форматов
- Строки стандартных числовых форматов
- Примечания Настройки панели управления
- Свойства NumberFormatInfo
- Целочисленные типы и типы с плавающей запятой
- Бесконечности действительных чисел с плавающей запятой и NaN
- Строки настраиваемых числовых форматов19
- Примечания Бесконечности действительных чисел с плавающей запятой и NaN
- Настройки панели управления
- Строки формата с фиксированной запятой и округлением
- Разделители секций и условное форматирование20
- Два примера настраиваемых форматов
- Регулярные выражения в .Net Framework
- Регулярные выражения как язык
- Escape-знаки
- Выполнение действия со строками с помощью основных строковых операций
- Разбор строк
- Разбор числовых строк
- Операторы и выражения
- Операторы
- Выражения
- Литералы и простые имена
- Выражения вызова
- Операторы
- Анонимные функции
- Эволюция делегатов в c#
- Лямбда-выражения22
- Выражения-лямбды
- Лямбды операторов
- Лямбды со стандартными операторами запросов
- Вывод типа в лямбда-выражениях
- Область действия переменной в лямбда-выражениях
- Использование лямбда-выражений вне linq
- Анонимные методы
- Заметки
- Перегружаемые операторы
- Операторы преобразования23
- Общие сведения об операторах преобразования
- Использование операторов преобразования
- Пример 1 Описание
- Результат 1
- Пример 2 Описание
- Результат 2
- Реализация определенных пользователем преобразований между структурами
- Надежное программирование
- Перегрузка операторов для реализации класса комплексных чисел
- Переопределение Equals
- Объекты, классы и структуры
- Интерфейсы
- Универсальные типы
- Статические типы
- Объекты
- Экземпляры структуры и экземпляры класса
- Идентификация объекта и идентификация значения26
- Объявление классов
- Создание объектов
- Наследование классов
- Описание
- Результат
- Общие сведения о классах
- Структуры
- Общие сведения о структурах
- Использование структур
- Пример 1 Описание
- Результат
- Пример 2 Описание
- Результат
- Наследование
- Абстрактные и запечатанные классы и члены классов
- Абстрактные классы и члены классов
- Запечатанные классы и члены классов
- Определение абстрактных свойств
- Полиморфизм
- Общие сведения о полиморфизме
- Управление версиями с помощью ключевых слов "Override" и "New"
- Переопределение и выбор метода29
- Использование ключевых слов "Override" и "New"
- Переопределение метода ToString
- Порядок переопределения метода OnString в классе или структуре
- Интерфейсы
- Общие сведения об интерфейсах
- Явная реализация интерфейса33
- Явная реализация членов интерфейса
- Надежное программирование
- Явная реализация членов интерфейса с наследованием
- Надежное программирование
- Параметры методов
- Возвращаемые значения
- Передача параметров
- Передача параметров типа значения
- Пример. Передача типов значений с помощью значения.
- Пример. Передача типов значений с помощью ссылки.
- Пример. Замена типов значений.
- Передача параметров ссылочного типа
- Пример. Передача ссылочных типов по значению
- Результат
- Рассмотрение кода
- Пример. Передача ссылочных типов по ссылке
- Результат
- Рассмотрение кода
- Пример. Перестановка двух строк
- Результат
- Рассмотрение кода
- Конструкторы
- Использование конструкторов
- Конструкторы экземпляров
- Пример 1
- Результат
- Пример 2
- Результат
- Пример 3
- Результат
- Закрытые конструкторы35
- Результат
- Статические конструкторы36
- Результат
- Создание конструктора копии
- Деструкторы
- Заметки
- Использование деструкторов для освобождения ресурсов.
- Высвобождение ресурсов явным образом
- Результат
- Инициализаторы объектов и коллекций
- Инициализаторы объектов и анонимные типы37
- Инициализаторы объектов и типы, допускающие значение null
- Инициализаторы коллекций
- Инициализация объектов без вызова конструктора
- Компиляция кода38
- Инициализация словаря с помощью инициализатора коллекции39
- Компиляция кода
- Константы
- Вложенные типы
- Модификаторы доступа
- Доступность класса и структуры
- Доступность члена класса и структуры
- Другие типы
- Разделяемые классы и методы40
- Разделяемый класс
- Ограничения
- Пример 1 Описание
- Результат
- Пример 2 Описание
- Разделяемые методы
- Статические классы и члены статических классов
- Статические классы
- Когда следует использовать статические классы
- Статические члены
- Входные данные
- Пример результатов выполнения.
- Определение различия между передачей структуры и ссылки класса в метод
- Анонимные типы41
- Заметки
- Возвращение поднаборов свойств элементов в запросе
- Компиляция кода
- Методы расширения
- Неявно типизированные локальные переменные
- Var и анонимные типы
- Заметки
- Свойства
- Результат
- Общие сведения о свойствах
- Использование свойств
- Метод доступа get
- Метод доступа set
- Заметки
- Пример 1 Описание
- Результат 1 Employee number: 101 Employee name: Claude Vige
- Пример 2 Описание
- Результат 2
- Рассмотрение кода
- Пример 3 Описание
- Введенные данные
- Результат 3
- Свойства интерфейса
- Пример результатов выполнения
- Асимметричные методы доступа
- Ограничения модификаторов доступа в методах доступа
- Модификаторы доступа в переопределяющих методах доступа
- Реализация интерфейсов
- Домен доступности к методу доступа
- Результат
- Примечания
- Объявление и использование свойств чтения и записи
- Надежное программирование
- Автоматически реализуемые свойства
- Реализация облегченного класса с автоматически реализуемыми свойствами
- Индексаторы
- Общие сведения об индексаторах
- Использование индексаторов
- Заметки
- Пример 1 Описание
- Индексирование с использованием других значений
- Пример 2 Описание
- Результат
- Надежное программирование
- Индексаторы в интерфейсах
- Результат
- Сравнение свойств и индексаторов
- Делегаты
- Общие сведения о делегатах
- Использование делегатов
- Делегаты с именованными методами и делегаты с анонимными методами
- Заметки
- Пример 1
- Результат
- Пример 2
- Результат
- Использование делегатов вместо интерфейсов
- Ковариация и контрвариация в делегатах
- Пример 1 (ковариация) Описание
- Пример 2 (контрвариация) Описание
- Объединение делегатов (многоадресные делегаты)
- Объявление, создание экземпляра и использование делегата
- Надежное программирование
- События
- Общие сведения о событиях
- Подписка и отмена подписки на события
- Подписка на события в среде ide Visual Studio
- Подписка на события программными средствами
- Подписка на события при помощи анонимного метода
- Отмена подписки
- Отмена подписки на событие
- Публикация событий, соответствующих рекомендациям .Net Framework
- Порядок публикации событий, основанных на шаблоне EventHandler
- Создание событий базового класса в производных классах
- Вызов и прием событий
- Реализация событий интерфейса
- Реализация событий интерфейса в классе
- Пример44
- Использование словаря для хранения экземпляров событий
- Универсальные шаблоны
- Общие сведения об универсальных шаблонах
- Введение в универсальные шаблоны
- Преимущества универсальных шаблонов
- Параметры универсального типа
- Рекомендации по именованию параметра типа
- Пространства имен
- Общие сведения о пространствах имен
- Использование пространств имен
- Доступ к пространствам имен
- Псевдонимы пространств имен
- Использование пространств имен для управления областью действия
- Полные имена
- Использование квалификатора псевдонима пространства имен
- Типы, допускающие значения null
- Общие сведения о типах, допускающих значения null
- Использование типов, допускающих значение null
- Примеры допускающих значение null типов
- Члены допускающих значение null типов
- Явные преобразования
- Неявные преобразования
- Операторы
- Оператор ??
- Идентификация типа, допускающего значение null
- Небезопасный код и указатели
- Общие сведения о небезопасном коде
- Буферы фиксированного размера
- Заметки
- Типы указателей45
- Преобразования указателей
- Неявные преобразования указателей
- Явные преобразования указателей
- Результат
- Выражения указателей Получение значения переменной указателя
- Получение адреса переменной
- Доступ к члену с использованием указателя
- Доступ к элементу массива с использованием указателя
- Управление указателями Увеличение и уменьшение указателей
- Арифметические операции над указателями
- Сравнение указателей
- Использование указателей для копирования массива байтов
- Комментарии xml-документации
- Рекомендуемые теги для комментариев документации
- Использование xml-документации
- Компиляция кода
- Надежное программирование
- Домены приложений
- Общие сведения о доменах приложений
- Выполнение кода в другом домене приложения
- Сборки и глобальный кэш сборок
- Общие сведения о сборках
- Атрибуты
- Общие сведения об атрибутах
- Использование атрибутов
- Общие атрибуты
- Заметки
- Использование нескольких идентификаторов
- Атрибут Obsolete
- Глобальные атрибуты
- Исключения и обработка исключений
- Общие сведения об исключениях
- Использование исключений
- Обработка исключений
- Блоки catch
- Блоки finally
- Создание и генерация исключений
- Чего следует избегать при генерации исключений
- Определение классов исключений
- Исключения, создаваемые компилятором
- Обработка исключений с помощью блока try-catch
- Примечания
- Выполнение кода очистки с использованием блока finally
- Взаимодействие
- Использование вызова неуправляемого кода для воспроизведения звукового файла
- Компиляция кода Чтобы скомпилировать этот код, выполните следующие действия47
- Создание потоков
- Общие сведения
- Использование потоков
- Синхронизация потоков
- Ключевое слово lock
- Мониторы
- События синхронизации и дескрипторы ожидания
- Мьютексные объекты
- Создание и завершение потоков
- Синхронизация потока-производителя и потока-потребителя
- Использование пула потоков
- Отражение
- Общие сведения об отражении
- Библиотеки c#
- Создание и использование библиотек dll на языке c#
- Выполнение
- Результат
- Компиляция кода
- Безопасность
- Рекомендации по безопасности, касающиеся языка c# в отдельности
- Использование неуправляемых функций dll
- Применение экспортированных функций dll
- Подробный обзор вызова неуправляемого кода
- Идентификация функций в библиотеках dll
- Создание класса, содержащего функции dll
- Создание прототипов в управляемом коде
- Основы описания
- Настройка описания
- Задание точки входа
- Вызов функции dll
- Передача структур
- Объявление и передача структур
- Объявление и передача классов
- Файловый и потоковый ввод-вывод
- Основы файлового ввода-вывода
- Классы, используемые в файловом вводе и выводе
- Классы, используемые для чтения и записи в поток
- Общие классы потокового ввода и вывода
- Ввод-вывод и безопасность
- Создание списка каталогов
- Надежное программирование
- Считывание из нового файла данных и запись в этот файл
- Надежное программирование
- Копирование каталогов
- Открытие файла журнала и добавление в него данных
- Запись текста в файл
- Считывание текста из файла
- Надежное программирование
- Считывание символов из строки
- Результат
- Запись символов в строку
- Надежное программирование
- Добавление или удаление записей списка управления доступом
- Чтобы добавить или удалить элемент списка управления доступом из файла
- Чтобы добавить или удалить элемент acl из каталога
- Компиляция кода
- Сжатие файлов
- Создание потоков
- Создание класса Writer
- Коллекции и структуры данных
- Определение коллекций
- Выбор класса коллекции
- Знакомство с решениями, проектами и элементами
- Контейнеры: проекты и решения
- Элементы: файлы, ссылки, подключения к данным
- Решения как контейнеры
- Решения
- Преимущества
- Файлы определения
- Проекты как контейнеры
- Шаблоны проектов
- Файлы проекта
- Элементы проектов
- Использование интегрированной среды разработки Visual c#
- Введение в интегрированную среду разработки
- Средства Visual c#
- Доступ к средствам в интегрированной среде разработки
- Окна редактора и конструктора форм Windows
- Обозреватель решений и конструктор проектов
- Окна компилятора, отладчика и списка ошибок
- Настройка интегрированной среды разработки
- Создание проекта
- Создание нового проекта
- Состав проекта Свойства
- Ресурсы
- Другие файлы исходного кода
- Изменение свойств проекта
- Создание пользовательского интерфейса
- Добавление элементов управления
- Задание свойств
- Обработка событий
- Редактирование кода
- Списки завершения
- Краткие сведения
- Список членов
- Сведения о параметрах
- Добавление директив using
- Оптимизация кода
- Фрагменты кода
- Подчеркивание волнистой линией
- Средства обеспечения удобочитаемости кода Форматирование кода
- Структура
- Выделение цветом
- Навигация и поиск
- Представление классов
- Навигация ctrl-tab
- Панели переходов
- Поиск в файлах
- Обозреватель объектов
- Стеки навигации
- Построение и отладка
- Параметры построения
- Ошибки построения
- Сравнение отладочной и выпускной конфигураций
- Отладка
- Моделирование и анализ кода
- Конструктор классов
- Обозреватель объектов
- Метаданные как источник
- Анализ управляемого кода
- Добавление и редактирование ресурсов
- Добавление ресурсов в проекты
- Редактирование ресурсов
- Компиляция ресурсов в сборки
- Доступ к ресурсам во время выполнения
- Получение справки
- Локальная справка и справка в Интернете
- Поиск по f1
- Указатель
- Содержание
- Инструкции
- Динамическая справка
- Примеры
- Оптимизация
- Многопроектная оптимизация
- Диалоговое окно "Предварительный просмотр изменений"
- Допускающая наличие ошибок оптимизация
- Извлечение метода
- Оптимизация кода с помощью операции "извлечение метода"
- Чтобы воспользоваться операцией "извлечение метода"
- Переименовать
- Операции переименования
- Переименование идентификаторов
- Чтобы переименовать идентификатор
- Превращение локальной переменной в параметр
- Заметки
- Превращение локальной переменной в параметр
- Чтобы выполнить превращение локальной переменной в параметр
- Разметка кода цветом
- Лексемы
- Контекстные ключевые слова
- Разметка цветом для обозначения парности фигурных скобок
- Разметка цветом и жирным шрифтом
- Разметка цветом и выделение цветным фоном