2009-01-25 25 views
9

如何做一個枚舉值和一個應該與枚舉名稱匹配的字符串的簡單比較?如何測試String = Enum.Value?

如何將字符串解析爲適當的枚舉值。

例如,

Enum A 
    B=0 
    C=1 
    D=2 
End Enum 

如何檢查是否字符串= A.C,我如何轉換成字符串及其對應的值,而不相對於一個字符串表示?

+2

,如果你總是希望枚舉值爲0(零)開始,你不需要說出來,只是BCD就足夠了 – balexandre 2009-01-25 00:13:12

+0

我不知道,謝謝你的提示。 – Middletone 2009-01-25 00:30:10

回答

17

但是也有一些相關的幾種不同的方法:

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無那些真正的工作。

5

Enum.GetName(typeof(A),enumValue)==stringValue

7

Enum.Parse方法:

的 名稱或一個或更多 枚舉常數的數值字符串表示轉換爲 等效枚舉對象。 A 參數指定 操作是否區分大小寫。

下面是從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 
2

您也可以使用名稱()函數的方式來檢查這個

A.C.name() == "C"