logo
CSharp_Prog_Guide

Порядок обработки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.