How to list Enum's members

后端 未结 4 1846
不思量自难忘°
不思量自难忘° 2021-02-04 02:36

How to list Enum\'s members in code? I have the following Enum:

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


        
4条回答
  •  伪装坚强ぢ
    2021-02-04 02:46

    I have used George Filippakos answer since I wanted to know how to iterate through Enum values.

    I also found out that you can do it using Type.GetEnumValues which has been available since .NET Framework 4.0.

    Here's the two ways you can use to iterate through Enum Values:

    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
    

    Output:

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

提交回复
热议问题