如何在代码中列出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
答案 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)
答案 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