列舉型別格式字串
您可以使用 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.