Метод ToString и описатели формата 


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



ЗНАЕТЕ ЛИ ВЫ?

Метод ToString и описатели формата



Платформа.NET Framework поддерживает перегрузку метода типа по умолчанию ToString, выполняющего элементарное форматирование, используя для этого специальную версию метода ToString, использующего параметр описателя формата для указания как нужно форматировать значение.

 


Format Providers

Format providers supply information such as the character to use as the decimal point when formatting numeric strings, or the separation character to use when formatting a DateTime object. Format providers define the characters used for formatting by the format specifiers, but do not define the specifiers themselves.

A format provider can either be passed to the overload of ToString required by the IFormattable interface, or be predetermined by the method you are using to format text if no format provider is passed.

When no format provider is passed, the information is either inferred, or obtained from one of the standard format providers included in the.NET Framework. Generally, classes that implement IFormattable also provide overloads of ToString that accept only a format specifier or only a format provider. The default ToString method, which accepts no parameters, is inherited from the Object class.

Composite Formatting

The.NET Framework composite formatting feature, which is supported by methods such as String..::.Format and the output methods of System..::.Console and System.IO..::.TextWriter, replaces each indexed format item embedded in a source string with the formatted equivalent of a corresponding element in a list of values. For more information, see Composite Formatting.

 


Поставщики формата

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

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

Если поставщик формата не был передан, то для получения требуемых сведений используются стандартные поставщики формата, включенные в состав платформы.NET Framework. Классы, в которых реализован интерфейс IFormattable, предоставляют переопределенный метод ToString, передавать которому можно либо описатель формата, либо поставщик формата. Метод по умолчанию ToString, который не принимает параметры, наследуется от класса Object.

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

Функция составного форматирования.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);

 



Поделиться:


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

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