Enum.GetName与Enum.ToString [英] Enum.GetName vs Enum.ToString

查看:74
本文介绍了Enum.GetName与Enum.ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此枚举,

Enum MyEnum
    Value
End Enum

有两种方法可以获取 MyEnum.Value 的名称表示形式 Value :

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

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

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

他们的优缺点是什么?毕竟哪个更好?

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

PS::一个答案(对于Java),但这是.NET,可能具有不同的功能.

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

推荐答案

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

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

和此代码

    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)

这篇关于Enum.GetName与Enum.ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆