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

Составное форматирование

Функция составного форматирования .NET Framework, которая поддерживается такими методами, как String..::.Format, методами вывода System..::.Console и System.IO..::.TextWriter, заменяет каждый встроенный в исходную строку индексированный элемент форматирования отформатированным эквивалентом соответствующего элемента в списке значений.

Formatting Base Types

Use formatting to convert a standard .NET Framework data type to a string that represents that type in some meaningful way. For example, if you have an integer value of 100 that you want to represent as a currency value, you can use the ToString method and the currency format string ("C") to produce a string of "$100.00". Note that computers that do not have U.S. English specified as the current culture will display whatever currency notation is used by the current culture.

To format a base type, pass the desired format specifier, the desired format provider, or both to the ToString method of the object you want to format. If you do not specify a format specifier, or if you pass null, then "G" (the general format) is used as the default. If you do not specify a format provider, if you pass null, or if the provider you specify does not have the property pertaining to the requested action, the format provider associated with the current thread is used.

In the following example, the ToString method displays the value 100 as a currency-formatted string to the console.

int MyInt = 100;

String MyString = MyInt.ToString("C");

Console.WriteLine(MyString);

Форматирование базовых типов

Форматирование служит для преобразования стандартных типов данных .NET Framework в строку и последующего отображения. Например, чтобы отобразить целое значение 100 в виде денежных единиц, воспользуйтесь методом ToString и строкой формата денежных единиц ("С"), чтобы создать строку "$100.00". Обратите внимание, что на компьютерах с выбранным языком и региональными параметрами, отличным от "Английского (США)", эта строка будет отображена в условных единицах установленного языком и региональными параметрами.

Чтобы отформатировать базовый тип, при вызове метода ToString для требуемого вида следует задать спецификатор формата и/или поставщика формата. Если спецификатор формата не задан или в качестве параметра передано значение null, то по умолчанию будет использован указатель "G" (общий формат). Если поставщик формата не задан, или в качестве параметра передано значение null, или если для поставщика не заданы требуемые для выполнения форматирования свойства, то будет использован поставщик формата, связанный с текущим потоком.

В следующем примере метод ToString показывает значение 100 как строку денежного формата на консоли.

int MyInt = 100;

String MyString = MyInt.ToString("C");

Console.WriteLine(MyString);

Formatting for Different Cultures

For most methods, the values returned using one of the string format specifiers have the ability to dynamically change based on the current culture or a specified culture. For example, an overload of the ToString method accepts a format provider that implements the IFormatProvider interface. Classes that implement this interface can specify characters to use for decimal and thousand separators and the spelling and placement of currency symbols. If you do not use an override that takes this parameter, the ToString method will use characters specified by the current culture.

The following example uses the CultureInfo class to specify the culture that the ToString method and format string will use. This code creates a new instance of the CultureInfo class called MyCulture and initializes it to the French culture using the string fr-FR. This object is passed to the ToString method with the C string format specifier to produce a French monetary value.

int MyInt = 100;

CultureInfo MyCulture = new CultureInfo("fr-FR");

String MyString = MyInt.ToString("C", MyCulture);

Console.WriteLine(MyString);

The preceding code displays 100,00 when displayed in a Windows Forms form. Note that the console environment does not support all Unicode characters and displays 100,00 ? instead.