如何对枚举值和应与枚举名称匹配的字符串进行简单比较?
如何将字符串解析为适当的枚举值.
例如,
Enum A B=0 C=1 D=2 End Enum
如何检查String = AC以及如何将字符串转换为相应的A值而不将其与字符串表示进行比较?
有几种不同的方法是相关的:
Enum.GetName(typeof(A), A.C) == "C" A.C.ToString() == "C" ((A)Enum.Parse(typeof(A), "C")) == A.C
前两个将值转换A.C
为字符串表示("C"
),然后将其与字符串进行比较.最后一个将字符串"C"
转换为类型A
,然后作为实际类型进行比较A
.
枚举到字符串:enumValue.ToString()
或Enum.GetName(typeof(A), A.C)
字符串到枚举: (A)Enum.Parse(typeof(A), "C")
请注意,如果枚举标记为,则这些都不会真正起作用FlagsAttribute
.
该Enum.Parse方法:
将一个或多个枚举常量的名称或数值的字符串表示形式转换为等效的枚举对象.参数指定操作是否区分大小写.
这是来自MSDN的VB.NET示例代码:
Module Example Public Sub Main() Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"} For Each colorString As String In colorStrings Try Dim colorValue As Colors = CType([Enum].Parse(GetType(Colors), colorString, True), Colors) If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString()) Else Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString) End If Catch e As ArgumentException Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString) End Try Next End Sub End Module
Enum.GetName(typeof(A),enumValue)==stringValue