Get VB.net Enum Description from Value

前端 未结 2 847
情话喂你
情话喂你 2020-12-17 14:02

How can I get Enum description from its value?

I can get the description from the name using:

Public Shared Function GetEnumDescription(         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 14:55

    Here's another solution to get an Enum's description as an extension.

    Imports System.ComponentModel
    Imports System.Runtime.CompilerServices
    
     Public Function GetEnumDescription(ByVal EnumConstant As [Enum]) As String
        Dim attr() As DescriptionAttribute = DirectCast(EnumConstant.GetType().GetField(EnumConstant.ToString()).GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
        Return If(attr.Length > 0, attr(0).Description, EnumConstant.ToString)
    End Function
    

    Example use from the previous posts:

    Enum Example
         Value1 = 1
         Value2 = 2
    End Enum
    
    Sub Main()
        Console.WriteLine(DirectCast(2, Example).GetEnumDescription())
        Console.ReadLine()
    End Sub
    

提交回复
热议问题