Enum.GetName vs Enum.ToString

别等时光非礼了梦想. 提交于 2021-02-08 15:11:23

问题


For this enumeration,

Enum MyEnum
    Value
End Enum

there are two methods to get the name representation Value of MyEnum.Value:

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

and

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

What are their pros and cons? And which is better after all?

PS: There is one answer for java but this is .NET which may have different functionality.


回答1:


Here are some examples of what can be done using this enum, note the usage of the flags attribute.

    <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

and this code

    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)


来源:https://stackoverflow.com/questions/37895901/enum-getname-vs-enum-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!