枚举格式字符串
可以使用 Enum.ToString 方法创建新的字符串对象,以表示枚举成员的数值、十六进制值或字符串值。 此方法采用某个枚举格式化字符串指定希望返回的值。
下表列出了枚举格式化字符串及其返回的值。 这些格式说明符不区分大小写。
示例
下面的示例定义一个名为 Colors 的枚举,该枚举包含三项:Red、Blue 和 Green。
Public Enum Color
Red = 1
Blue = 2
Green = 3
End Enum
public enum Color {Red = 1, Blue = 2, Green = 3}
定义了枚举后,可以按下面的方式声明实例。
Dim myColor As Color = Color.Green
Color myColor = Color.Green;
随后,Color.ToString(System.String) 方法可用于以不同的方式显示枚举值,具体则取决于传递给它的格式说明符。
Console.WriteLine("The value of myColor is {0}.", _
myColor.ToString("G"))
Console.WriteLine("The value of myColor is {0}.", _
myColor.ToString("F"))
Console.WriteLine("The value of myColor is {0}.", _
myColor.ToString("D"))
Console.WriteLine("The value of myColor is 0x{0}.", _
myColor.ToString("X"))
' The example displays the following output to the console:
' The value of myColor is Green.
' The value of myColor is Green.
' The value of myColor is 3.
' The value of myColor is 0x00000003.
Console.WriteLine("The value of myColor is {0}.",
myColor.ToString("G"));
Console.WriteLine("The value of myColor is {0}.",
myColor.ToString("F"));
Console.WriteLine("The value of myColor is {0}.",
myColor.ToString("D"));
Console.WriteLine("The value of myColor is 0x{0}.",
myColor.ToString("X"));
// The example displays the following output to the console:
// The value of myColor is Green.
// The value of myColor is Green.
// The value of myColor is 3.
// The value of myColor is 0x00000003.