mercredi 27 mai 2020

How can I show an enum like the Visual Studio tooltip?

I have the following class:

Public Class PetClass

    Public Enum Animal
         Bird = 1
         Dog = 2
         Cat = 3
    End Enum

    Public MyPetType As Animal = Animal.Cat

    (...)
End Class

When I move the mouse over MyPetType, VS shows the following:

enter image description here

I would like to print this using Debug.

I'm using the following code to do this:

<Extension()>
Public Function Description(ByVal EnumConstant As [Enum]) As String
    Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    If aattr.Length > 0 Then
        Return aattr(0).Description
    Else
        Return EnumConstant.ToString()
    End If
End Function

Then I use it like this:

Dim n As New PetClass
Debug.Print(Description(n.MyPetType))

The output is "Cat".

When I debug the function and hover the mouse over the last line, it shows exactely what I want to output:

enter image description here

However, the results of the function is "Cat" and not "Cat {3}".

How could I make it output "Cat {3}"?





Aucun commentaire:

Enregistrer un commentaire