Enum.GetName vs Enum.ToString

时间:2016-06-18 10:23:01

标签: .net vb.net enums tostring

对于此枚举,

Enum MyEnum
    Value
End Enum

有两种方法可以获取Value的名称代表MyEnum.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,可能有不同的功能。

1 个答案:

答案 0 :(得分:3)

以下是使用此枚举可以完成的一些示例,请注意flags属性的用法。

    <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)