How to list Enum's members
如何在代码中列出枚举的成员?我有以下列举:
1 2 3 4 5 6 | Public Enum TestEnum As int32 First = 0 Second = 2 Third = 4 Fourth = 6 End Enum |
我试图通过以下代码列出testenum的所有成员,但失败了:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
所以,我的问题是:如何列出枚举的成员?
更新:解决方案是:
1 2 3 4 5 6 7 8 9 10 |
您需要向方法传递一个类型,而不是值。
1 | Members = System.Enum.GetNames(GetType(TestEnum)) |
如果有枚举的实例,也可以使用
1 | Members = System.Enum.GetNames(Enum1.GetType()) |
如果你知道你想要的类型,我会推荐第一种方法。
您可以简单地迭代如下所示的所有值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
你看过Enum.GetValues吗?
编辑:要澄清,是的,您需要将类型而不是枚举的实例传递给这两个方法。
1 | Enum.GetNames(GetType(TestEnum)) |
我使用George Filippakos的答案,因为我想知道如何迭代
我还发现您可以使用从
下面是两种迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
输出:
1 2 3 4 5 6 7 | Name: First, Value: 1 Name: Second, Value: 2 Name: Third, Value: 3 Name: First, Value: 1 Name: Second, Value: 2 Name: Third, Value: 3 |