Enum.ToString Метод
Определение
Преобразует значение этого экземпляра в эквивалентное ему строковое представление.Converts the value of this instance to its equivalent string representation.
Перегрузки
ToString(IFormatProvider) |
Является устаревшей.
Перегруженная версия метода является устаревшей, вместо нее следует использовать метод ToString().This method overload is obsolete; use ToString(). |
ToString(String) |
Преобразует числовое значение этого экземпляра в эквивалентное ему строковое представление с использованием указанного формата.Converts the value of this instance to its equivalent string representation using the specified format. |
ToString(String, IFormatProvider) |
Является устаревшей.
Эта перегрузка метода является устаревшей. Используйте ToString(String).This method overload is obsolete; use ToString(String). |
ToString() |
Преобразует значение этого экземпляра в эквивалентное ему строковое представление.Converts the value of this instance to its equivalent string representation. |
ToString(IFormatProvider)
Внимание!
The provider argument is not used. Please use ToString().
Перегруженная версия метода является устаревшей, вместо нее следует использовать метод ToString().This method overload is obsolete; use ToString().
public:
virtual System::String ^ ToString(IFormatProvider ^ provider);
public string ToString (IFormatProvider? provider);
[System.Obsolete("The provider argument is not used. Please use ToString().")]
public string ToString (IFormatProvider provider);
[System.Obsolete("The provider argument is not used. Please use ToString().")]
public string ToString (IFormatProvider? provider);
public string ToString (IFormatProvider provider);
override this.ToString : IFormatProvider -> string
[<System.Obsolete("The provider argument is not used. Please use ToString().")>]
override this.ToString : IFormatProvider -> string
Public Function ToString (provider As IFormatProvider) As String
Параметры
- provider
- IFormatProvider
(Является устаревшим.)(obsolete)
Возвращаемое значение
Строковое представление значения этого экземпляра.The string representation of the value of this instance.
Реализации
- Атрибуты
Применяется к
ToString(String)
Преобразует числовое значение этого экземпляра в эквивалентное ему строковое представление с использованием указанного формата.Converts the value of this instance to its equivalent string representation using the specified format.
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 format string.
Возвращаемое значение
Строковое представление значения данного экземпляра, определяемое параметром format
.The string representation of the value of this instance as specified by format
.
Исключения
format
содержит недопустимую спецификацию.format
contains an invalid specification.
Параметр format
равен X, но тип перечисления неизвестен.format
equals "X", but the enumeration type is unknown.
Примеры
В следующем примере показано, как преобразовать перечислимое значение в строку.The following example demonstrates how to convert an enumerated value to a string.
// Sample for Enum::ToString(String)
using namespace System;
public enum class Colors
{
Red, Green, Blue, Yellow = 12
};
int main()
{
Colors myColor = Colors::Yellow;
Console::WriteLine( "Colors::Red = {0}", Colors::Red.ToString( "d" ) );
Console::WriteLine( "Colors::Green = {0}", Colors::Green.ToString( "d" ) );
Console::WriteLine( "Colors::Blue = {0}", Colors::Blue.ToString( "d" ) );
Console::WriteLine( "Colors::Yellow = {0}", Colors::Yellow.ToString( "d" ) );
Console::WriteLine( " {0}myColor = Colors::Yellow {0}", Environment::NewLine );
Console::WriteLine( "myColor->ToString(\"g\") = {0}", myColor.ToString( "g" ) );
Console::WriteLine( "myColor->ToString(\"G\") = {0}", myColor.ToString( "G" ) );
Console::WriteLine( "myColor->ToString(\"x\") = {0}", myColor.ToString( "x" ) );
Console::WriteLine( "myColor->ToString(\"X\") = {0}", myColor.ToString( "X" ) );
Console::WriteLine( "myColor->ToString(\"d\") = {0}", myColor.ToString( "d" ) );
Console::WriteLine( "myColor->ToString(\"D\") = {0}", myColor.ToString( "D" ) );
Console::WriteLine( "myColor->ToString(\"f\") = {0}", myColor.ToString( "f" ) );
Console::WriteLine( "myColor->ToString(\"F\") = {0}", myColor.ToString( "F" ) );
}
/*
This example produces the following results:
Colors::Red = 0
Colors::Green = 1
Colors::Blue = 2
Colors::Yellow = 12
myColor = Colors::Yellow
myColor->ToString("g") = Yellow
myColor->ToString("G") = Yellow
myColor->ToString("x") = 0000000C
myColor->ToString("X") = 0000000C
myColor->ToString("d") = 12
myColor->ToString("D") = 12
myColor->ToString("f") = Yellow
myColor->ToString("F") = Yellow
*/
// Sample for Enum.ToString(String)
using System;
class Sample
{
enum Colors {Red, Green, Blue, Yellow = 12};
public static void Main()
{
Colors myColor = Colors.Yellow;
Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"));
Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d"));
Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"));
Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"));
Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);
Console.WriteLine("myColor.ToString(\"g\") = {0}", myColor.ToString("g"));
Console.WriteLine("myColor.ToString(\"G\") = {0}", myColor.ToString("G"));
Console.WriteLine("myColor.ToString(\"x\") = {0}", myColor.ToString("x"));
Console.WriteLine("myColor.ToString(\"X\") = {0}", myColor.ToString("X"));
Console.WriteLine("myColor.ToString(\"d\") = {0}", myColor.ToString("d"));
Console.WriteLine("myColor.ToString(\"D\") = {0}", myColor.ToString("D"));
Console.WriteLine("myColor.ToString(\"f\") = {0}", myColor.ToString("f"));
Console.WriteLine("myColor.ToString(\"F\") = {0}", myColor.ToString("F"));
}
}
/*
This example produces the following results:
Colors.Red = 0
Colors.Green = 1
Colors.Blue = 2
Colors.Yellow = 12
myColor = Colors.Yellow
myColor.ToString("g") = Yellow
myColor.ToString("G") = Yellow
myColor.ToString("x") = 0000000C
myColor.ToString("X") = 0000000C
myColor.ToString("d") = 12
myColor.ToString("D") = 12
myColor.ToString("f") = Yellow
myColor.ToString("F") = Yellow
*/
' Sample for Enum.ToString(String)
Class Sample
Enum Colors
Red
Green
Blue
Yellow = 12
End Enum 'Colors
Public Shared Sub Main()
Dim myColor As Colors = Colors.Yellow
Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"))
Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d"))
Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"))
Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"))
Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine)
Console.WriteLine("myColor.ToString(""g"") = {0}", myColor.ToString("g"))
Console.WriteLine("myColor.ToString(""G"") = {0}", myColor.ToString("G"))
Console.WriteLine("myColor.ToString(""x"") = {0}", myColor.ToString("x"))
Console.WriteLine("myColor.ToString(""X"") = {0}", myColor.ToString("X"))
Console.WriteLine("myColor.ToString(""d"") = {0}", myColor.ToString("d"))
Console.WriteLine("myColor.ToString(""D"") = {0}", myColor.ToString("D"))
Console.WriteLine("myColor.ToString(""f"") = {0}", myColor.ToString("f"))
Console.WriteLine("myColor.ToString(""F"") = {0}", myColor.ToString("F"))
End Sub
End Class
'
'This example produces the following results:
'
'Colors.Red = 0
'Colors.Green = 1
'Colors.Blue = 2
'Colors.Yellow = 12
'
'myColor = Colors.Yellow
'
'myColor.ToString("g") = Yellow
'myColor.ToString("G") = Yellow
'myColor.ToString("x") = 0000000C
'myColor.ToString("X") = 0000000C
'myColor.ToString("d") = 12
'myColor.ToString("D") = 12
'myColor.ToString("f") = Yellow
'myColor.ToString("F") = Yellow
'
Комментарии
format
Параметр может быть одной из следующих строк формата: "G" или "g", "d", "d", "x", "x", "f" или "f" (строка формата не учитывает регистр).The format
parameter can be one of the following format strings: "G" or "g", "D" or "d", "X" or "x", and "F" or "f" (the format string is not case-sensitive). Если format
параметр имеет значение null
или является пустой строкой (""), используется описатель общего формата ("G").If format
is null
or an empty string (""), the general format specifier ("G") is used. Дополнительные сведения о строках формата перечисления и значениях перечисления форматирования см. в разделе строки формата перечисления.For more information about the enumeration format strings and formatting enumeration values, see Enumeration Format Strings. Дополнительные сведения о форматировании в целом см. в разделе Типы форматирования.For more information about formatting in general, see Formatting Types.
Примечания для тех, кто вызывает этот метод
Если несколько членов перечисления имеют одинаковое базовое значение и вы пытаетесь получить строковое представление имени члена перечисления на основе его базового значения, код не должен делать никаких предположений о том, какое имя будет возвращено методом.If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return. Например, следующее перечисление определяет два члена: затенять. Gray
и Shader. Grey
, имеющие одно и то же базовое значение.For example, the following enumeration defines two members, Shade.Gray
and Shade.Grey
, that have the same underlying value.
[! код-CSharpSystem. Enum. ToString # 1] [! код-VBSystem. Enum. ToString # 1][!code-csharpSystem.Enum.ToString#1] [!code-vbSystem.Enum.ToString#1]
Следующий вызов метода пытается получить имя элемента перечисления заливки
, базовое значение которого равно 1.The following method call attempts to retrieve the name of a member of the Shade
enumeration whose underlying value is 1. Метод может возвращать "серый" или "серый", и код не должен делать никаких предположений о том, какая строка будет возвращена.The method can return either "Gray" or "Grey", and your code should not make any assumptions about which string will be returned.
[! код-CSharpSystem. Enum. ToString # 3] [! код-VBSystem. Enum. ToString # 3][!code-csharpSystem.Enum.ToString#3] [!code-vbSystem.Enum.ToString#3]
См. также раздел
- Format(Type, Object, String)
- Parse(Type, String)
- ToString(String, IFormatProvider)
- Типы форматирования в .NETFormatting Types in .NET
- Строки форматов перечисленияEnumeration Format Strings
Применяется к
ToString(String, IFormatProvider)
Внимание!
The provider argument is not used. Please use ToString(String).
Эта перегрузка метода является устаревшей. Используйте ToString(String).This method overload is obsolete; use ToString(String).
public:
virtual System::String ^ ToString(System::String ^ format, IFormatProvider ^ provider);
public string? ToString (string format, IFormatProvider provider);
[System.Obsolete("The provider argument is not used. Please use ToString(String).")]
public string ToString (string format, IFormatProvider provider);
[System.Obsolete("The provider argument is not used. Please use ToString(String).")]
public string? ToString (string format, IFormatProvider provider);
public string ToString (string format, IFormatProvider provider);
override this.ToString : string * IFormatProvider -> string
[<System.Obsolete("The provider argument is not used. Please use ToString(String).")>]
override this.ToString : string * IFormatProvider -> string
Public Function ToString (format As String, provider As IFormatProvider) As String
Параметры
- format
- String
Спецификация формата.A format specification.
- provider
- IFormatProvider
(Является устаревшим.)(Obsolete.)
Возвращаемое значение
Строковое представление значения данного экземпляра, определяемое параметром format
.The string representation of the value of this instance as specified by format
.
Реализации
- Атрибуты
Исключения
Формат format
не содержит допустимой спецификации формата.format
does not contain a valid format specification.
Параметр format
равен X, но тип перечисления неизвестен.format
equals "X", but the enumeration type is unknown.
Комментарии
format
Параметр может быть одной из следующих строк формата: "G" или "g", "d", "d", "x", "x", "f" или "f" (строка формата не учитывает регистр).The format
parameter can be one of the following format strings: "G" or "g", "D" or "d", "X" or "x", and "F" or "f" (the format string is not case-sensitive). Если format
параметр имеет значение null
или является пустой строкой (""), используется описатель общего формата ("G").If format
is null
or an empty string (""), the general format specifier ("G") is used. Дополнительные сведения о строках формата перечисления и значениях перечисления форматирования см. в разделе строки формата перечисления.For more information about the enumeration format strings and formatting enumeration values, see Enumeration Format Strings. Дополнительные сведения о форматировании в целом см. в разделе Типы форматирования.For more information about formatting in general, see Formatting Types.
Указывать только format
; provider
параметр является устаревшим.Specify only format
; the provider
parameter is obsolete.
См. также раздел
- Format(Type, Object, String)
- Типы форматирования в .NETFormatting Types in .NET
- Строки форматов перечисленияEnumeration Format Strings
Применяется к
ToString()
Преобразует значение этого экземпляра в эквивалентное ему строковое представление.Converts the value of this instance to its equivalent string representation.
public:
override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String
Возвращаемое значение
Строковое представление значения этого экземпляра.The string representation of the value of this instance.
Примеры
В следующем примере показано преобразование перечислимого значения в строку.The following example demonstrates converting an enumerated value to a string.
using namespace System;
public ref class EnumSample
{
public:
enum class Colors
{
Red = 1,
Blue = 2
};
static void main()
{
Enum ^ myColors = Colors::Red;
Console::WriteLine( "The value of this instance is '{0}'", myColors );
}
};
int main()
{
EnumSample::main();
}
/*
Output.
The value of this instance is 'Red'.
*/
using System;
public class EnumSample {
enum Colors {Red = 1, Blue = 2};
public static void Main() {
Enum myColors = Colors.Red;
Console.WriteLine("The value of this instance is '{0}'",
myColors.ToString());
}
}
/*
Output.
The value of this instance is 'Red'.
*/
Public Class EnumSample
Enum Colors
Red = 1
Blue = 2
End Enum
Public Shared Sub Main()
Dim myColors As Colors = Colors.Red
Console.WriteLine("The value of this instance is '{0}'", _
myColors.ToString())
End Sub
End Class
'Output.
'The value of this instance is 'Red'.
Комментарии
Возвращаемое значение форматируется с помощью общего описателя формата ("G").The return value is formatted with the general format specifier ("G"). То есть если объект FlagsAttribute не применяется к этому перечислимому типу и существует именованная константа, равная значению этого экземпляра, то возвращаемое значение является строкой, содержащей имя константы.That is, if the FlagsAttribute is not applied to this enumerated type and there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant. Если FlagsAttribute применяется, и существует сочетание одной или нескольких именованных констант, равное значению этого экземпляра, то возвращаемое значение является строкой, содержащей разделенный разделителем список имен констант.If the FlagsAttribute is applied and there is a combination of one or more named constants equal to the value of this instance, then the return value is a string containing a delimiter-separated list of the names of the constants. В противном случае возвращаемое значение является строковым представлением числового значения данного экземпляра.Otherwise, the return value is the string representation of the numeric value of this instance. Дополнительные сведения о форматировании значений перечисления см. в разделе строки формата перечисления.For more information about formatting enumeration values, see Enumeration Format Strings. Дополнительные сведения о форматировании в целом см. в разделе Типы форматирования.For more information about formatting in general, see Formatting Types.
Примечания для тех, кто вызывает этот метод
Если несколько членов перечисления имеют одинаковое базовое значение и вы пытаетесь получить строковое представление имени члена перечисления на основе его базового значения, код не должен делать никаких предположений о том, какое имя будет возвращено методом.If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return. Например, следующее перечисление определяет два члена: затенять. Gray
и Shader. Grey
, имеющие одно и то же базовое значение.For example, the following enumeration defines two members, Shade.Gray
and Shade.Grey
, that have the same underlying value.
[! код-CSharpSystem. Enum. ToString # 1] [! код-VBSystem. Enum. ToString # 1][!code-csharpSystem.Enum.ToString#1] [!code-vbSystem.Enum.ToString#1]
Следующий вызов метода пытается получить имя элемента перечисления заливки
, базовое значение которого равно 1.The following method call attempts to retrieve the name of a member of the Shade
enumeration whose underlying value is 1. Метод может возвращать "серый" или "серый", и код не должен делать никаких предположений о том, какая строка будет возвращена.The method can return either "Gray" or "Grey", and your code should not make any assumptions about which string will be returned.
[! код-CSharpSystem. Enum. ToString # 2] [! код-VBSystem. Enum. ToString # 2][!code-csharpSystem.Enum.ToString#2] [!code-vbSystem.Enum.ToString#2]