DotNet · 2022年2月26日

使用DescriptionAttribute,返回单条字符串信息和字符串列表的源码

''' <summary>
    ''' 获取在枚举中定义的字符串表达式
    ''' </summary>
    ''' <param name="pEnumValue"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function getValueDescription(ByVal pEnumValue As [Enum]) As String
        Dim pFI As FieldInfo = pEnumValue.GetType().GetField(pEnumValue.ToString())
        Dim pDesc As DescriptionAttribute = Attribute.GetCustomAttribute(pFI, GetType(DescriptionAttribute), True)
        If (pDesc IsNot Nothing) Then
            Return pDesc.Description
        Else
            Return pEnumValue.ToString()            '如果没有定义,就返回自身的字符串表达
        End If
    End Function


    Public Shared Sub getValueDescriptionList(ByVal pEnumType As Type)
        If (pEnumType.IsEnum = False) Then
            Throw New TypeLoadException("getValueDescriptionList只支持枚举类型,当前传递的类型" & pEnumType.FullName & "不是枚举类型")
        End If


        Dim pList As New System.Collections.Generic.List(Of String)
        For Each pField As FieldInfo In pEnumType.GetFields()
            Dim pDesc As DescriptionAttribute = Attribute.GetCustomAttribute(pField, GetType(DescriptionAttribute), True)
            If (pDesc IsNot Nothing) Then
                pList.Add(pDesc.Description)
                Debug.Print(pField.GetValue(pEnumType))
            End If
        Next
        Debug.Print(pList.Count)
    End Sub

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞