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


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

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



В большинстве методов значения, возвращаемые с помощью одного из спецификаторов формата, могут динамически изменяться в зависимости от текущих и заданных региональных параметров. Например, перегруженный метод 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.


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

В качестве входных данных для составного форматирования в.NET Framework используется список объектов и строка составного формата. Строка составного формата состоит из фиксированного текста, в который включены индексированные местозаполнители, которые называются элементами форматирования и соответствуют объектам из списка. Операция форматирования создает результирующую строку, состоящую из исходного фиксированного текста, в который включено строковое представление объектов из списка.

Составное форматирование поддерживается такими методами, как Format и AppendFormat, а также некоторыми перегрузками методов WriteLine и TextWriter..::.WriteLine. Метод String..::.Format возвращает отформатированную результирующую строку, метод AppendFormat добавляет отформатированную результирующую строку к объекту StringBuilder, метод Console..::.WriteLine выводит отформатированную результирующую строку на консоль, а метод TextWriter..::.WriteLine записывает отформатированную результирующую строку в поток или файл.

Строка составного формата

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

Рассмотрим следующий фрагмент кода Format.

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

Фиксированным текстом здесь является "Name = " и ", hours = ". Элементы форматирования здесь — это "{0}" c индексом 0, который соответствует объекту myName, и "{1:hh}" с индексом 1, который соответствует объекту DateTime.Now.


Format Item Syntax

Each format item takes the following form and consists of the following components:

{index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

 




Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 108; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 52.14.240.178 (0.004 с.)