Imports System.ComponentModel
Imports System.Reflection

Namespace EnumExtend
    ''' <summary>
    ''' 枚举扩展类
    ''' </summary>
    Public Class EnumExtender
        ''' <summary>
        ''' 获取枚举描述特性
        ''' </summary>
        ''' <param name="enumValue">需要获取特性的枚举值</param>
        ''' <returns>枚举描述特性</returns>
        Public Shared Function GetEnumDescription(enumValue As [Enum]) As String
            Dim field As FieldInfo = enumValue.GetType().GetField(enumValue.ToString())
            Dim attributes() As DescriptionAttribute =
                    DirectCast(field.GetCustomAttributes(GetType(DescriptionAttribute),
                                                         False), DescriptionAttribute())
            If attributes.Length > 0 Then
                Return attributes(0).Description
            Else
                Return field.Name
            End If

        End Function

        ''' <summary>
        ''' 获取当前枚举所有描述特性值,未填的枚举采用枚举名
        ''' </summary>
        ''' <param name="enumType">枚举类型</param>
        ''' <returns></returns>
        Public Shared Function GetEnumAllDesc(enumType As Type) As String()
            Dim fields As FieldInfo() = enumType.GetFields( BindingFlags.Static Or BindingFlags.Public)
            Dim fieldsDesc As New List(Of String)
            For Each field As FieldInfo In fields
                Dim attributes() As DescriptionAttribute =
                        DirectCast(field.GetCustomAttributes(GetType(DescriptionAttribute),
                                                          False), DescriptionAttribute())
                If attributes.Length > 0 Then
                    fieldsDesc.Add(attributes(0).Description)
                Else
                    fieldsDesc.Add(field.Name)
                End If
            Next
            Return fieldsDesc.ToArray()
        End Function
    End Class
End Namespace