Byte.ToString Метод
Определение
Перегрузки
ToString(IFormatProvider) |
Преобразует числовое значение текущего объекта Byte в эквивалентное ему строковое представление с использованием указанных сведений об особенностях форматирования для данного языка и региональных параметров.Converts the numeric value of the current Byte object to its equivalent string representation using the specified culture-specific formatting information. |
ToString(String, IFormatProvider) |
Преобразует числовое значение текущего объекта Byte в эквивалентное ему строковое представление с использованием указанного формата и сведений об особенностях форматирования для данного языка и региональных параметров.Converts the value of the current Byte object to its equivalent string representation using the specified format and culture-specific formatting information. |
ToString(String) |
Преобразует значение текущего объекта Byte в эквивалентное ему строковое представление с использованием заданного формата.Converts the value of the current Byte object to its equivalent string representation using the specified format. |
ToString() |
Преобразует значение текущего объекта Byte в эквивалентное ему строковое представление.Converts the value of the current Byte object to its equivalent string representation. |
ToString(IFormatProvider)
Преобразует числовое значение текущего объекта Byte в эквивалентное ему строковое представление с использованием указанных сведений об особенностях форматирования для данного языка и региональных параметров.Converts the numeric value of the current Byte object to its equivalent string representation using the specified culture-specific formatting information.
public:
virtual System::String ^ ToString(IFormatProvider ^ provider);
public:
System::String ^ ToString(IFormatProvider ^ provider);
public string ToString (IFormatProvider provider);
public string ToString (IFormatProvider? provider);
override this.ToString : IFormatProvider -> string
Public Function ToString (provider As IFormatProvider) As String
Параметры
- provider
- IFormatProvider
Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.An object that supplies culture-specific formatting information.
Возвращаемое значение
Строковое представление значения данного объекта в формате, заданном в параметре provider
.The string representation of the value of this object in the format specified by the provider
parameter.
Реализации
Примеры
В следующем примере выполняется итерация массива байтовых значений и отображение каждого из них в консоли путем вызова ToString(IFormatProvider) метода с различными поставщиками формата.The following example iterates an array of byte values and displays each of them to the console by calling the ToString(IFormatProvider) method with different format providers.
array<Byte>^ bytes = gcnew array<Byte> {0, 1, 14, 168, 255};
array<CultureInfo^>^ providers = {gcnew CultureInfo("en-us"),
gcnew CultureInfo("fr-fr"),
gcnew CultureInfo("de-de"),
gcnew CultureInfo("es-es")};
for each (Byte byteValue in bytes)
{
for each (CultureInfo^ provider in providers)
Console::Write("{0,3} ({1}) ",
byteValue.ToString(provider), provider->Name);
Console::WriteLine();
}
// The example displays the following output to the console:
// 0 (en-US) 0 (fr-FR) 0 (de-DE) 0 (es-ES)
// 1 (en-US) 1 (fr-FR) 1 (de-DE) 1 (es-ES)
// 14 (en-US) 14 (fr-FR) 14 (de-DE) 14 (es-ES)
// 168 (en-US) 168 (fr-FR) 168 (de-DE) 168 (es-ES)
// 255 (en-US) 255 (fr-FR) 255 (de-DE) 255 (es-ES)
byte[] bytes = {0, 1, 14, 168, 255};
CultureInfo[] providers = {new CultureInfo("en-us"),
new CultureInfo("fr-fr"),
new CultureInfo("de-de"),
new CultureInfo("es-es")};
foreach (byte byteValue in bytes)
{
foreach (CultureInfo provider in providers)
Console.Write("{0,3} ({1}) ",
byteValue.ToString(provider), provider.Name);
Console.WriteLine();
}
// The example displays the following output to the console:
// 0 (en-US) 0 (fr-FR) 0 (de-DE) 0 (es-ES)
// 1 (en-US) 1 (fr-FR) 1 (de-DE) 1 (es-ES)
// 14 (en-US) 14 (fr-FR) 14 (de-DE) 14 (es-ES)
// 168 (en-US) 168 (fr-FR) 168 (de-DE) 168 (es-ES)
// 255 (en-US) 255 (fr-FR) 255 (de-DE) 255 (es-ES)
Dim bytes() As Byte = {0, 1, 14, 168, 255}
Dim providers() As CultureInfo = {New CultureInfo("en-us"), _
New CultureInfo("fr-fr"), _
New CultureInfo("de-de"), _
New CultureInfo("es-es")}
For Each byteValue As Byte In bytes
For Each provider As CultureInfo In providers
Console.Write("{0,3} ({1}) ", byteValue.ToString(provider), provider.Name)
Next
Console.WriteLine()
Next
' The example displays the following output to the console:
' 0 (en-US) 0 (fr-FR) 0 (de-DE) 0 (es-ES)
' 1 (en-US) 1 (fr-FR) 1 (de-DE) 1 (es-ES)
' 14 (en-US) 14 (fr-FR) 14 (de-DE) 14 (es-ES)
' 168 (en-US) 168 (fr-FR) 168 (de-DE) 168 (es-ES)
' 255 (en-US) 255 (fr-FR) 255 (de-DE) 255 (es-ES)
Комментарии
Возвращаемое значение форматируется с помощью описателя общего числового формата ("G").The return value is formatted with the general numeric format specifier ("G").
provider
Параметр — это объект, реализующий IFormatProvider интерфейс.The provider
parameter is an object that implements the IFormatProvider interface. Его GetFormat метод возвращает NumberFormatInfo объект, предоставляющий сведения о формате строки, возвращаемой этим методом, в зависимости от языка и региональных параметров.Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of the string that is returned by this method. Объект, реализующий, IFormatProvider может быть любым из следующих:The object that implements IFormatProvider can be any of the following:
CultureInfoОбъект, представляющий язык и региональные параметры, правила форматирования которых будут использоваться.A CultureInfo object that represents the culture whose formatting rules are to be used.
NumberFormatInfoОбъект, содержащий конкретные сведения о форматировании для этого значения.A NumberFormatInfo object that contains specific numeric formatting information for this value.
Пользовательский объект, реализующий интерфейс IFormatProvider .A custom object that implements IFormatProvider.
Если provider
параметр имеет null
NumberFormatInfo значение или объект не может быть получен из provider
, возвращаемые значения форматируются с использованием NumberFormatInfo объекта для текущего языка и региональных параметров потока.If provider
is null
or a NumberFormatInfo object cannot be obtained from provider
, the return value is formatted using the NumberFormatInfo object for the thread current culture. Сведения о текущем языке и региональных параметрах потока см. в разделе Thread.CurrentCulture .For information about the thread current culture, see Thread.CurrentCulture.
.NET обеспечивает обширную поддержку форматирования, которая подробно описывается в следующих разделах форматирования:.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:
Дополнительные сведения о спецификаторах числовых форматов см. в разделе строки стандартных числовых форматов и строки настраиваемых числовых форматов.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Дополнительные сведения о форматировании см. в разделе Типы форматирования.For more information about formatting, see Formatting Types.
См. также раздел
Применяется к
ToString(String, IFormatProvider)
Преобразует числовое значение текущего объекта Byte в эквивалентное ему строковое представление с использованием указанного формата и сведений об особенностях форматирования для данного языка и региональных параметров.Converts the value of the current Byte object to its equivalent string representation using the specified format and culture-specific formatting information.
public:
virtual System::String ^ ToString(System::String ^ format, IFormatProvider ^ provider);
public string ToString (string format, IFormatProvider provider);
public string ToString (string? format, IFormatProvider? provider);
override this.ToString : string * IFormatProvider -> string
Public Function ToString (format As String, provider As IFormatProvider) As String
Параметры
- format
- String
Стандартная или пользовательская строка числового формата.A standard or custom numeric format string.
- provider
- IFormatProvider
Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.An object that supplies culture-specific formatting information.
Возвращаемое значение
Строковое представление текущего объекта Byte, отформатированное, как указано в параметрах format
и provider
.The string representation of the current Byte object, formatted as specified by the format
and provider
parameters.
Реализации
Исключения
format
содержит неподдерживаемый спецификатор.format
includes an unsupported specifier. Спецификаторы поддерживаемого формата перечислены в разделе "Примечания".Supported format specifiers are listed in the Remarks section.
Примеры
В следующем примере используется стандартная строка формата N и четыре различных CultureInfo объекта для отображения строкового представления байтового значения в консоли.The following example uses the standard "N" format string and four different CultureInfo objects to display the string representation of a byte value to the console.
Byte byteValue = 250;
array<CultureInfo^>^ providers = gcnew array<CultureInfo^> { gcnew CultureInfo("en-us"),
gcnew CultureInfo("fr-fr"),
gcnew CultureInfo("es-es"),
gcnew CultureInfo("de-de")};
for each (CultureInfo^ provider in providers)
Console::WriteLine("{0} ({1})",
byteValue.ToString("N2", provider), provider->Name);
// The example displays the following output to the console:
// 250.00 (en-US)
// 250,00 (fr-FR)
// 250,00 (es-ES)
// 250,00 (de-DE)
byte byteValue = 250;
CultureInfo[] providers = {new CultureInfo("en-us"),
new CultureInfo("fr-fr"),
new CultureInfo("es-es"),
new CultureInfo("de-de")};
foreach (CultureInfo provider in providers)
Console.WriteLine("{0} ({1})",
byteValue.ToString("N2", provider), provider.Name);
// The example displays the following output to the console:
// 250.00 (en-US)
// 250,00 (fr-FR)
// 250,00 (es-ES)
// 250,00 (de-DE)
Dim byteValue As Byte = 250
Dim providers() As CultureInfo = {New CultureInfo("en-us"), _
New CultureInfo("fr-fr"), _
New CultureInfo("es-es"), _
New CultureInfo("de-de")}
For Each provider As CultureInfo In providers
Console.WriteLine("{0} ({1})", _
byteValue.ToString("N2", provider), provider.Name)
Next
' The example displays the following output to the console:
' 250.00 (en-US)
' 250,00 (fr-FR)
' 250,00 (es-ES)
' 250,00 (de-DE)
Комментарии
ToString(String, IFormatProvider)Метод форматирует Byte значение в указанном формате указанного языка и региональных параметров.The ToString(String, IFormatProvider) method formats a Byte value in a specified format of a specified culture. Чтобы отформатировать число с помощью стандартного формата ("G") текущего языка и региональных параметров, вызовите ToString() метод.To format a number by using the default ("G") format of the current culture, call the ToString() method. Чтобы отформатировать число с использованием указанного формата текущего языка и региональных параметров, вызовите ToString(String) метод.To format a number by using a specified format of the current culture, call the ToString(String) method.
format
Параметр может быть либо стандартной, либо строкой настраиваемого числового формата.The format
parameter can be either a standard or a custom numeric format string. Поддерживаются все строки стандартного числового формата, отличные от "R" (или "r"), как и все пользовательские символы числового формата.All standard numeric format strings other than "R" (or "r") are supported, as are all custom numeric format characters. Если format
параметр имеет null
значение или является пустой строкой (""), то возвращаемое значения этого метода форматируется с помощью описателя общего числового формата ("G").If format
is null
or an empty string (""), the return value of this method is formatted with the general numeric format specifier ("G").
provider
Параметр — это объект, реализующий IFormatProvider интерфейс.The provider
parameter is an object that implements the IFormatProvider interface. Его GetFormat метод возвращает NumberFormatInfo объект, предоставляющий сведения о формате строки, возвращаемой этим методом, в зависимости от языка и региональных параметров.Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of the string that is returned by this method. Объект, реализующий, IFormatProvider может быть любым из следующих:The object that implements IFormatProvider can be any of the following:
CultureInfoОбъект, представляющий язык и региональные параметры, правила форматирования которых будут использоваться.A CultureInfo object that represents the culture whose formatting rules are to be used.
NumberFormatInfoОбъект, содержащий конкретные сведения о форматировании для этого значения.A NumberFormatInfo object that contains specific numeric formatting information for this value.
Пользовательский объект, реализующий интерфейс IFormatProvider .A custom object that implements IFormatProvider.
Если provider
параметр имеет null
NumberFormatInfo значение или объект не может быть получен из provider
, возвращаемые значения форматируются с использованием NumberFormatInfo объекта для текущего языка и региональных параметров потока.If provider
is null
or a NumberFormatInfo object cannot be obtained from provider
, the return value is formatted using the NumberFormatInfo object for the thread current culture. Сведения о текущем языке и региональных параметрах потока см. в разделе Thread.CurrentCulture .For information about the thread current culture, see Thread.CurrentCulture.
.NET обеспечивает обширную поддержку форматирования, которая подробно описывается в следующих разделах форматирования:.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:
Дополнительные сведения о спецификаторах числовых форматов см. в разделе строки стандартных числовых форматов и строки настраиваемых числовых форматов.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Дополнительные сведения о форматировании см. в разделе Типы форматирования.For more information about formatting, see Formatting Types.
См. также раздел
- Parse(String)
- String
- NumberFormatInfo
- IFormattable
- IFormatProvider
- Типы форматирования в .NETFormatting Types in .NET
- Практическое руководство. Добавление к числу начальных нулей.How to: Pad a Number with Leading Zeros
- Пример: служебная программа форматирования .NET Core WinForms (C#)Sample: .NET Core WinForms Formatting Utility (C#)
- Пример: служебная программа форматирования .NET Core WinForms (Visual Basic)Sample: .NET Core WinForms Formatting Utility (Visual Basic)
Применяется к
ToString(String)
public:
System::String ^ ToString(System::String ^ format);
public string ToString (string format);
public string ToString (string? format);
override this.ToString : string -> string
Public Function ToString (format As String) As String
Параметры
- format
- String
Строка числового формата.A numeric format string.
Возвращаемое значение
Строковое представление текущего объекта Byte, отформатированное, как указано в параметре format
.The string representation of the current Byte object, formatted as specified by the format
parameter.
Исключения
format
содержит неподдерживаемый спецификатор.format
includes an unsupported specifier. Спецификаторы поддерживаемого формата перечислены в разделе "Примечания".Supported format specifiers are listed in the Remarks section.
Примеры
В следующем примере инициализируется Byte значение и отображается в консоли с использованием каждой из поддерживаемых стандартных строк стандартного формата и строки настраиваемого формата.The following example initializes a Byte value and displays it to the console using each of the supported standard format strings and a custom format string. Пример выполняется с EN-US в качестве текущего языка и региональных параметров.The example is run with en-US as the current culture.
array<String^>^ formats = gcnew array<String^> {"C3", "D4", "e1", "E2", "F1", "G", "N1",
"P0", "X4", "0000.0000"};
Byte number = 240;
for each (String^ format in formats)
Console::WriteLine("'{0}' format specifier: {1}",
format, number.ToString(format));
// The example displays the following output to the console if the
// current culture is en-us:
// 'C3' format specifier: $240.000
// 'D4' format specifier: 0240
// 'e1' format specifier: 2.4e+002
// 'E2' format specifier: 2.40E+002
// 'F1' format specifier: 240.0
// 'G' format specifier: 240
// 'N1' format specifier: 240.0
// 'P0' format specifier: 24,000 %
// 'X4' format specifier: 00F0
// '0000.0000' format specifier: 0240.0000
string[] formats = {"C3", "D4", "e1", "E2", "F1", "G", "N1",
"P0", "X4", "0000.0000"};
byte number = 240;
foreach (string format in formats)
Console.WriteLine("'{0}' format specifier: {1}",
format, number.ToString(format));
// The example displays the following output to the console if the
// current culture is en-us:
// 'C3' format specifier: $240.000
// 'D4' format specifier: 0240
// 'e1' format specifier: 2.4e+002
// 'E2' format specifier: 2.40E+002
// 'F1' format specifier: 240.0
// 'G' format specifier: 240
// 'N1' format specifier: 240.0
// 'P0' format specifier: 24,000 %
// 'X4' format specifier: 00F0
// '0000.0000' format specifier: 0240.0000
Dim formats() As String = {"C3", "D4", "e1", "E2", "F1", "G", _
"N1", "P0", "X4", "0000.0000"}
Dim number As Byte = 240
For Each format As String In formats
Console.WriteLine("'{0}' format specifier: {1}", _
format, number.ToString(format))
Next
' The example displays the following output to the console if the
' current culture is en-us:
' 'C3' format specifier: $240.000
' 'D4' format specifier: 0240
' 'e1' format specifier: 2.4e+002
' 'E2' format specifier: 2.40E+002
' 'F1' format specifier: 240.0
' 'G' format specifier: 240
' 'N1' format specifier: 240.0
' 'P0' format specifier: 24,000 %
' 'X4' format specifier: 00F0
' '0000.0000' format specifier: 0240.0000
Комментарии
format
Параметр может быть либо стандартной, либо строкой настраиваемого числового формата.The format
parameter can be either a standard or a custom numeric format string. Поддерживаются все строки стандартного числового формата, отличные от "R" (или "r"), как и все пользовательские символы числового формата.All standard numeric format strings other than "R" (or "r") are supported, as are all custom numeric format characters. Если format
параметр имеет null
значение или является пустой строкой (""), возвращаемые значения форматируются с помощью описателя общего числового формата ("G").If format
is null
or an empty string (""), the return value is formatted with the general numeric format specifier ("G").
Возвращаемое значение этой функции форматируется с использованием NumberFormatInfo объекта для текущего языка и региональных параметров потока.The return value of this function is formatted using the NumberFormatInfo object for the thread current culture. Сведения о текущем языке и региональных параметрах потока см. в разделе Thread.CurrentCulture .For information about the thread current culture, see Thread.CurrentCulture. Чтобы предоставить сведения о форматировании для языков и региональных параметров, отличных от текущего языка и региональных параметров, вызовите Byte.ToString(String, IFormatProvider) метод.To provide formatting information for cultures other than the current culture, call the Byte.ToString(String, IFormatProvider) method.
.NET обеспечивает обширную поддержку форматирования, которая подробно описывается в следующих разделах форматирования:.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:
Дополнительные сведения о спецификаторах числовых форматов см. в разделе строки стандартных числовых форматов и строки настраиваемых числовых форматов.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Дополнительные сведения о форматировании см. в разделе Типы форматирования.For more information about formatting, see Formatting Types.
Применяется к
ToString()
public:
override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String
Возвращаемое значение
Строковое представление значения данного объекта, состоящее из последовательности цифр в диапазоне от 0 до 9 без начальных нулей.The string representation of the value of this object, which consists of a sequence of digits that range from 0 to 9 with no leading zeroes.
Примеры
В следующем примере отображается массив байтовых значений.The following example displays an array of byte values. Обратите внимание, что ToString() метод не вызывается явным образом в примере.Note that the ToString() method is not called explicitly in the example. Вместо этого он вызывается неявно из-за использования функции составного форматирования .Instead, it is called implicitly, because of the use of the composite formatting feature.
array<Byte>^ bytes = gcnew array<Byte> {0, 1, 14, 168, 255};
for each (Byte byteValue in bytes)
Console::WriteLine(byteValue);
// The example displays the following output to the console if the current
// culture is en-US:
// 0
// 1
// 14
// 168
// 255
byte[] bytes = {0, 1, 14, 168, 255};
foreach (byte byteValue in bytes)
Console.WriteLine(byteValue);
// The example displays the following output to the console if the current
// culture is en-US:
// 0
// 1
// 14
// 168
// 255
Dim bytes() As Byte = {0, 1, 14, 168, 255}
For Each byteValue As Byte In Bytes
Console.WriteLine(byteValue)
Next
' The example displays the following output to the console if the current
' culture is en-US:
' 0
' 1
' 14
' 168
' 255
Комментарии
Возвращаемое значение форматируется с помощью описателя общего числового формата ("G") и NumberFormatInfo объекта для текущего языка и региональных параметров потока.The return value is formatted with the general numeric format specifier ("G") and the NumberFormatInfo object for the thread current culture. Чтобы определить форматирование Byte строкового представления значения, вызовите ToString метод.To define the formatting of the Byte value's string representation, call the ToString method. Чтобы определить как описатели формата, так и язык и региональные параметры, используемые для создания строкового представления Byte значения, вызовите ToString метод.To define both the format specifiers and culture used to create the string representation of a Byte value, call the ToString method.
.NET обеспечивает обширную поддержку форматирования, которая подробно описывается в следующих разделах форматирования:.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:
Дополнительные сведения о спецификаторах числовых форматов см. в разделе строки стандартных числовых форматов и строки настраиваемых числовых форматов.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Дополнительные сведения о форматировании см. в разделе Типы форматирования.For more information about formatting, see Formatting Types.
Сведения о текущем языке и региональных параметрах потока см. в разделе Thread.CurrentCulture .For information about the thread current culture, see Thread.CurrentCulture.