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

Форматирование для различных языков и региональных параметров16

В большинстве методов значения, возвращаемые с помощью одного из спецификаторов формата, могут динамически изменяться в зависимости от текущих и заданных региональных параметров. Например, перегруженный метод ToString принимает поставщика формата, реализующего интерфейс IFormatProvider. С помощью классов, реализующих этот интерфейс, можно задавать знак-разделитель целой и дробной частей числа, знак-разделитель тысяч, знак валюты и его расположение. Если переопределенный метод не получает этих параметров, при вызове метода ToString будут использованы знаки, определенные в текущих региональных параметрах.

В следующем примере используется класс CultureInfo для указания региональных параметров, которые будут использоваться методом ToString и строками форматирования. Этот код создает новый экземпляр класса CultureInfo с именем MyCulture и инициализирует его с использованием региональных параметров для Франции и строки fr-FR. Чтобы получить строку в денежном формате Франции, объект передается методу ToString со спецификатором формата строки C.

int MyInt = 100;

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

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

Console.WriteLine(MyString);

Предыдущий код выводит строку 100,00 на форму Windows Forms. Обратите внимание, что среда консоли не поддерживает все символы Юникод. В консоли будет отображена строка 100,00 ?.

The following example illustrates how to modify the CultureInfo object associated with the current thread. This sample assumes that U.S. English (en-US) is the culture associated with the current thread and shows how to change that culture through code. This sample also demonstrates how to specify a particular culture by passing a modified CultureInfo to a ToString method and how to pass a new DateTimeFormatInfo to a ToString method.

DateTime dt = DateTime.Now;

DateTimeFormatInfo dfi = new DateTimeFormatInfo();

CultureInfo ci = new CultureInfo("de-DE");

// Create a new custom time pattern for demonstration.

dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";

// Use the DateTimeFormat from the culture associated with

// the current thread.

Console.WriteLine( dt.ToString("d") );

Console.WriteLine( dt.ToString("m") );

// Use the DateTimeFormat object from the specific culture passed.

Console.WriteLine( dt.ToString("d", ci ) );

// Use the settings from the DateTimeFormatInfo object passed.

Console.WriteLine( dt.ToString("m", dfi ) );

// Reset the current thread to a different culture.

Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");

Console.WriteLine( dt.ToString("d") );

В следующем примере объясняется изменение объекта CultureInfo, связанного с текущим потоком. Демонстрируется программное изменение региональных параметров. Считается, что по умолчанию с текущим потоком связаны региональные параметры "Английский (США)". Этот пример также демонстрирует способ установки региональных параметров посредством передачи измененного объекта CultureInfo методу ToString, а также способ передачи нового объекта DateTimeFormatInfo методу ToString.

DateTime dt = DateTime.Now;

DateTimeFormatInfo dfi = new DateTimeFormatInfo();

CultureInfo ci = new CultureInfo("de-DE");

// Create a new custom time pattern for demonstration.

dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";

// Use the DateTimeFormat from the culture associated with

// the current thread.

Console.WriteLine( dt.ToString("d") );

Console.WriteLine( dt.ToString("m") );

// Use the DateTimeFormat object from the specific culture passed.

Console.WriteLine( dt.ToString("d", ci ) );

// Use the settings from the DateTimeFormatInfo object passed.

Console.WriteLine( dt.ToString("m", dfi ) );

// Reset the current thread to a different culture.

Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");

Console.WriteLine( dt.ToString("d") );

Composite Formatting

The .NET Framework composite formatting feature takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.

The composite formatting feature is supported by methods such as Format, AppendFormat, and some overloads of WriteLine and TextWriter..::.WriteLine. The String..::.Format method yields a formatted result string, the AppendFormat method appends a formatted result string to a StringBuilder object, the Console..::.WriteLine methods display the formatted result string to the console, and the TextWriter..::.WriteLine method writes the formatted result string to a stream or file.

Composite Format String

A composite format string and object list are used as arguments of methods that support the composite formatting feature. A composite format string consists of zero or more runs of fixed text intermixed with one or more format items. The fixed text is any string that you choose, and each format item corresponds to an object or boxed structure in the list. The composite formatting feature returns a new result string where each format item is replaced by the string representation of the corresponding object in the list.

Consider the following Format code fragment.

string myName = "Fred";

String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now);

The fixed text is "Name = " and ", hours = ". The format items are "{0}", whose index is 0, which corresponds to the object myName, and "{1:hh}", whose index is 1, which corresponds to the object DateTime.Now.