如何列出Enum的成员

时间:2011-06-07 17:28:35

标签: vb.net enums

如何在代码中列出Enum的成员?我跟随Enum:

Public Enum TestEnum As int32
    First = 0
    Second = 2
    Third = 4
    Fourth = 6
End Enum

我尝试通过以下代码列出TestEnum的所有成员,但失败了:

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim Enum1 As TestEnum

        Dim Members() As String

        Members = System.Enum.GetNames(CType(Enum1, System.Enum))


    End Sub
End Class

所以,我的问题是:如何列出枚举的成员?

更新:解决方案是:

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim Members() As String
        Members = System.Enum.GetNames(GetType(TestEnum))

        MessageBox.Show(Join(Members, Chr(13) & Chr(10)))

    End Sub
End Class

4 个答案:

答案 0 :(得分:15)

您需要将类型而不是值传递给方法。

Members = System.Enum.GetNames(GetType(TestEnum))

如果您有枚举实例,也可以使用

Members = System.Enum.GetNames(Enum1.GetType())

如果你知道你想要的类型,我会推荐第一种方法。

答案 1 :(得分:15)

您可以简单地遍历所有值,如下所示:

Public Enum TestEnum As int32
    First = 0
    Second = 2
    Third = 4
    Fourth = 6
End Enum

For Each tstEnum As TestEnum In System.Enum.GetValues(GetType(TestEnum))

    Response.Write(
        String.Format("Name: {0}  Value: {1}", 
            tstEnum.ToString, 
            CInt(tstEnum).ToString
        )
    )

Next

答案 2 :(得分:8)

你看过Enum.GetValues吗?

编辑:澄清一下,是的,你需要将一个Type而不是枚举的实例传递给任一方法。

Enum.GetNames(GetType(TestEnum))

答案 3 :(得分:3)

我使用George Filippakos answer因为我想知道如何迭代Enum值。

我还发现您可以使用自.NET Framework 4.0以来可用的Type.GetEnumValues来完成此操作。

以下是您可以用来迭代Enum值的两种方法:

Module Module1
    Sub Main()
        For Each tstEnum As TestEnum In System.Enum.GetValues(GetType(TestEnum))
            Console.WriteLine($"Name: {tstEnum.ToString}, Value: {CType(tstEnum, Integer)}")
        Next

        Console.WriteLine(Environment.NewLine)

        For Each tstEnum As TestEnum In GetType(TestEnum).GetEnumValues
            Console.WriteLine($"Name: {tstEnum.ToString}, Value: {CType(tstEnum, Integer)}")
        Next

        Console.ReadKey()
    End Sub

    Public Enum TestEnum
        First = 1
        Second = 2
        Third = 3
    End Enum
End Module

输出:

Name: First, Value: 1
Name: Second, Value: 2
Name: Third, Value: 3

Name: First, Value: 1
Name: Second, Value: 2
Name: Third, Value: 3