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

Безопасность

Для проверки данных, введенных пользователем в такие элементы управления, как текстовые поля и поля со списком, всегда следует использовать метод TryParse или Parse.

Encoding Base Types

Characters are abstract entities that can be represented using many different character schemes or code pages. For example, Unicode UTF-16 encoding represents characters as sequences of 16-bit integers, whereas Unicode UTF-8 represents the same characters as sequences of 8-bit bytes. The common language runtime uses Unicode UTF-16 (Unicode Transformation Format, 16-bit encoding form) to represent characters.

Applications that target the common language runtime use encoding to map character representations from the native character scheme to other schemes. Applications use decoding to map characters from non-native schemes to the native scheme. The following table lists the most commonly used classes in the System.Text namespace to encode and decode characters.

Character Scheme

Class

Explanation

ASCII encoding

System.Text..::.ASCIIEncoding

Converts to and from ASCII characters.

Multiple encoding

System.Text..::.Encoding

Converts characters to and from various encodings as specified in the Convert method.

UTF-16 Unicode encoding

System.Text..::.UnicodeEncoding

Converts to and from UTF-16 encoding. This scheme represents characters as 16-bit integers.

UTF-8 Unicode encoding

System.Text..::.UTF8Encoding

Converts to and from UTF-8 encoding. This variable-width encoding scheme represents characters using one to four bytes.

Базовые типы кодировки

Знаки — это абстрактные сущности, которые представляются с помощью множества различных схем знаков или кодовых страниц. Например, в кодировке Юникод UTF-16 знаки представляются в виде последовательности 16-битовых целых чисел, в то время как в кодировке Юникод UTF-8 те же самые знаки описываются в виде последовательности 8-битовых байт. Среда CLR использует для представления знаков кодировку Юникод UTF-16 (Unicode Transformation Format, 16-битовая кодировка).

Для отображения представления знаков из внутренней схемы знаков во внешние схемы приложения, ориентированные на среду CLR, используется кодирование. Для обратного преобразования знаков из внешних схем во внутренние схемы приложения используется декодирование. В следующей таблице перечислены классы из пространства имен System.Text, наиболее часто используемые для кодирования и декодирования знаков.

Схема знаков

Класс

Объяснение

Кодировка ASCII

System.Text..::.ASCIIEncoding

Преобразование в знаки ASCII и обратное преобразование.

Многоформатная кодировка

System.Text..::.Encoding

Преобразование знаков в различные форматы кодировки и обратное преобразование в порядке, определяемом методом Convert.

Кодировка Юникод UTF-16

System.Text..::.UnicodeEncoding

Преобразование в формат UTF-16 и обратное преобразование. В этой схеме знаки представляются 16-битовыми целыми числами.

Кодировка Юникод UTF-8

System.Text..::.UTF8Encoding

Преобразование в формат UTF-8 и обратное преобразование. В этой схеме с переменной длиной представления знаки представляются с использованием от одного до четырех байт.

The following code example converts a Unicode string into an array of bytes using the ASCIIEncoding..::.GetBytes method. Each byte in the array represents the ASCII value for the letter in that position of the string.

string MyString = "Encoding String.";

ASCIIEncoding AE = new ASCIIEncoding();

byte[] ByteArray = AE.GetBytes(MyString);

for(int x = 0;x <= ByteArray.Length - 1; x++)

{

Console.Write("{0} ", ByteArray[x]);

}

This example displays the following to the console. The byte 69 is the ASCII value for the E character; the byte 110 is the ASCII value for the n character, and so on.

69 110 99 111 100 105 110 103 32 83 116 114 105 110 103 46

The following code example converts the preceding array of bytes into an array of characters using the ASCIIEncoding class. The GetChars method is used to decode the array of bytes.

ASCIIEncoding AE = new ASCIIEncoding();

byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 };

char[] CharArray = AE.GetChars(ByteArray);

for(int x = 0;x <= CharArray.Length - 1; x++)

{

Console.Write(CharArray[x]);

}

The preceding code displays the text Encoding String. to the console.

В следующем примере кода строка в формате Юникод преобразуется в байтовый массив с помощью метода ASCIIEncoding..::.GetBytes. Каждый байт массива представляет значение ASCII, соответствующее букве, находящейся в данном месте строки.

string MyString = "Encoding String.";

ASCIIEncoding AE = new ASCIIEncoding();

byte[] ByteArray = AE.GetBytes(MyString);

for(int x = 0;x <= ByteArray.Length - 1; x++)

{

Console.Write("{0} ", ByteArray[x]);

}

Ниже показан консольный вывод этого примера. Байт 69 — это значение ASCII для знака E; байт 110 — это значение ASCII для знака n и т. д.

69 110 99 111 100 105 110 103 32 83 116 114 105 110 103 46

В следующем примере кода происходит преобразование полученного выше байтового массива в массив знаков с помощью класса ASCIIEncoding. Для декодирования байтового массива используется метод GetChars.

ASCIIEncoding AE = new ASCIIEncoding();

byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 };

char[] CharArray = AE.GetChars(ByteArray);

for(int x = 0;x <= CharArray.Length - 1; x++)

{

Console.Write(CharArray[x]);

}

Приведенный выше код выводит на консоль текст Encoding String.

Formatting Types

The .NET Framework provides a consistent, flexible, and comprehensive means for you to represent any of the numeric, enumeration, and date and time base data types as a string. Formatting is controlled by strings of format specifier characters that indicate how a base type value is to be represented. For example, format specifiers indicate whether a formatted number should be represented in scientific notation, or whether a formatted date should present the month as a number or a name.

The .NET Framework also uses cultural settings to represent a base type in a form appropriate to a particular culture. You can supply custom cultural settings, or use the default cultural setting associated with the current thread. For example, when formatting a currency type, the cultural setting specifies the characters to use for the currency symbol, group separator, and decimal separator.

The .NET Framework allows you to define custom formatting schemes and custom cultural settings. This ability enables you to expand the formatting schemes of existing base types to accommodate custom scenarios, or create custom formatting schemes for custom types.

Formatting Overview

The .NET Framework provides a customizable, general-purpose formatting mechanism to convert a value into a string suitable for display. For example, a numeric value can be formatted in hexadecimal, scientific notation, or a series of digits separated into groups with a user-specified punctuation mark. Dates and times can be formatted as appropriate for a particular country, region, or culture. An enumerated constant can be formatted as its numeric value or its name.

You control formatting by specifying a format string and format provider, or by using the defaults. A format string contains one or more format specifier characters that indicate how a value is to be converted. A format provider supplies additional control, replacement, and cultural information required to convert a specific type.

You can override the way the .NET Framework interprets a format string by implementing the IFormattable interface, provide your own format provider by implementing the IFormatProvider interface, and perform your own formatting by implementing the ICustomFormatter interface.

The .NET Framework provides a feature called composite formatting that uses one or more format strings to embed one or more formatted values in a result string. The result string can be used for further processing, displayed to the system console, or written to a stream.