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

Порядок обработки18

При форматировании значения null возвращается пустая строка ("").

Если форматируемый тип реализует интерфейс ICustomFormatter, то вызывается метод ICustomFormatter..::.Format.

Если выполнение предыдущего шага не привело к форматированию типа и тип при этом реализует интерфейс IFormattable, то будет вызван метод IFormattable..::.ToString.

Если выполнение предыдущего шага не привело к форматированию типа, то вызывается метод ToString, который тип наследует от класса Object.

После выполнения предшествующих шагов производится выравнивание.

Code Examples

The following example shows one string created using composite formatting and another created using an object's ToString method. Both types of formatting produce equivalent results.

string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);

string FormatString2 = DateTime.Now.ToString("dddd MMMM");

Assuming that the current day is a Thursday in May, the value of both strings in the preceding example is Thursday May in the U.S. English culture.

Console.WriteLine exposes the same functionality as String.Format. The only difference between the two methods is that String.Format returns its result as a string, while Console.WriteLine writes the result to the output stream associated with the Console object. The following example uses the Console.WriteLine method to format the value of MyInt to a currency value.

int MyInt = 100;

Console.WriteLine("{0:C}", MyInt);

This code displays $100.00 to the console on computers that have U.S. English as the current culture.

The following example demonstrates formatting multiple objects, including formatting one object two different ways.

string myName = "Fred";

String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",

myName, DateTime.Now);

The output from the preceding string is "Name = Fred, hours = 07, minutes = 23", where the current time reflects these numbers.

Примеры кода

В приведенном ниже примере одна строка создается с помощью составного форматирования, а другая — с помощью метода ToString. Оба способа форматирования дают идентичные результаты.

string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);

string FormatString2 = DateTime.Now.ToString("dddd MMMM");

Предположим, что сейчас май, а текущий день недели — четверг; тогда значение обеих строк для языка и региональных параметров "Английский (США)" в предыдущем примере будет равно Thursday May.

Метод Console.WriteLine обладает той же функциональностью, что и String.Format. Единственное различие между двумя методами состоит в том, что метод String.Format возвращает результат в виде строки, а Console.WriteLine записывает результат в выходной поток, связанный с объектом Console.

В следующем примере для форматирования значения переменной MyInt в виде денежной единицы используется метод Console.WriteLine.

int MyInt = 100;

Console.WriteLine("{0:C}", MyInt);

На тех компьютерах, где выбраны языковые и региональные параметры "Английский (США)", этот код будет выводить на консоль строку $100.00.

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

string myName = "Fred";

String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",

myName, DateTime.Now);

Результатом обработки приведенной выше строки станет строка "Name = Fred, hours = 07, minutes = 23", числа в которой соответствуют текущему времени.

The following examples demonstrate the use of alignment in formatting. The arguments that are formatted are placed between vertical bar characters (|) to highlight the resulting alignment.

string myFName = "Fred";

string myLName = "Opals";

int myInt = 100;

string FormatFName = String.Format("First Name = |{0,10}|", myFName);

string FormatLName = String.Format("Last Name = |{0,10}|", myLName);

string FormatPrice = String.Format("Price = |{0,10:C}|", myInt);

Console.WriteLine(FormatFName);

Console.WriteLine(FormatLName);

Console.WriteLine(FormatPrice);

FormatFName = String.Format("First Name = |{0,-10}|", myFName);

FormatLName = String.Format("Last Name = |{0,-10}|", myLName);

FormatPrice = String.Format("Price = |{0,-10:C}|", myInt);

Console.WriteLine(FormatFName);

Console.WriteLine(FormatLName);

Console.WriteLine(FormatPrice);

The preceding code displays the following to the console in the U.S. English culture. Different cultures display different currency symbols and separators.

First Name = | Fred|

Last Name = | Opals|

Price = | $100.00|

First Name = |Fred |

Last Name = |Opals |

Price = |$100.00 |

Ниже приведен пример использования выравнивания при форматировании. Форматируемые аргументы разделены знаками вертикальной черты ("|"), подчеркивающими полученное выравнивание.

--------------

При выборе языка и региональных параметров "Английский (США)" этот код выведет на консоль следующий текст. При выборе различных языковых и региональных параметров знаки денежных единиц и разделители также различаются.

First Name = | Fred|

Last Name = | Opals|

Price = | $100.00|

First Name = |Fred |

Last Name = |Opals |

Price = |$100.00 |

Numeric Format Strings

Numeric format strings control formatting operations in which a numeric data type is represented as a string.

Numeric format strings fall into two categories:

  • Standard numeric format strings.

Standard numeric format strings consist of one of a set of standard numeric format specifiers. Each standard format specifier denotes a particular, commonly used string representation of numeric data.

  • Custom numeric format strings.

Custom format strings consist of one or more custom numeric format specifiers. Combine custom numeric format specifiers to define an application-specific pattern that determines how numeric data is formatted.

Numeric format strings are supported by the ToString method of numeric types. Numeric format strings are also supported by the .NET Framework composite formatting feature, which is used by certain Write and WriteLine methods of the Console and StreamWriter classes, the String..::.Format method, and the StringBuilder..::.AppendFormat method.

Standard Numeric Format Strings

Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form Axx, where A is an alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string.

The following table describes the standard numeric format specifiers and displays sample output produced by each format specifier. For more information, see the notes that follow the table.