Get VB.net Enum Description from Value

前端 未结 2 842
情话喂你
情话喂你 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:53

    If you have a variable of your enum type, it's simply

    GetEnumDescription(myEnum)
    

    Minimal working example:

    Enum TestEnum
        
        Value1
    End Enum
    
    Public Sub Main()
        Dim myEnum As TestEnum = TestEnum.Value1
        Console.WriteLine(GetEnumDescription(myEnum)) ' prints "Description of Value1"
        Console.ReadLine()
    End Sub
    

    If you have an Integer variable, you need to cast it to your enum type first (CType works as well):

    GetEnumDescription(DirectCast(myEnumValue, TestEnum))
    

    Working example:

    Enum TestEnum
        
        Value1 = 1
    End Enum
    
    Public Sub Main()
        Console.WriteLine(GetEnumDescription(DirectCast(1, TestEnum)))
        Console.ReadLine()
    End Sub
    

    The source for your confusion seems to be a misunderstanding: Your method does not take the "name" of an enum as a parameter, it takes an Enum as a parameter. That's something different, and it's also the reason why your attempts to use GetName failed.

提交回复
热议问题