2016-06-18 63 views
2

此枚舉,Enum.GetName VS Enum.ToString

Enum MyEnum 
    Value 
End Enum 

有兩種方法來獲取名字表示ValueMyEnum.Value的:

[Enum].GetName(GetType(MyEnum), MyEnum.Value) ' aka Enum.GetName 

Dim a As MyEnum = MyEnum.Value 
a.ToString ' aka Enum.ToString 

什麼他們的優點和缺點?畢竟哪個更好?

PS:對於java有one answer,但這是.NET,它可能有不同的功能。

+4

'ToString'可以處理與多個標誌'Flag'屬性枚舉。 – PetSerAl

回答

3

這裏有什麼可以使用此枚舉來完成一些例子,注意標誌屬性的使用。

<Flags> 
    Public Enum bit As Short 
     none = 0 
     s0 = 1 << 0 
     s1 = 1 << 1 
     s2 = 1 << 2 
     s3 = 1 << 3 
     s4 = 1 << 4 
     s5 = 1 << 5 
     s6 = 1 << 6 
     s7 = 1 << 7 
     s8 = 1 << 8 
     s9 = 1 << 9 
     s10 = 1 << 10 
     s11 = 1 << 11 
     s12 = 1 << 12 
     s13 = 1 << 13 
     s14 = 1 << 14 
     all = -1 
    End Enum 

和驗證碼

Dim s As String = bit.s13.ToString 
    s = (bit.s10 Or bit.s11).ToString 

    Dim foo() As String 
    foo = [Enum].GetNames(GetType(bit)) 

    For Each s As String In foo 
     Debug.WriteLine(s) 
    Next 

    Dim test As bit = bit.s1 Or bit.s3 Or bit.s5 
    Debug.WriteLine(test.ToString) 
    Debug.WriteLine(CShort(test).ToString) 

    test = test Or CType([Enum].Parse(GetType(bit), "s14"), bit) 
    Debug.WriteLine(test.ToString) 
相關問題