Define String ENUM in VB.Net

后端 未结 6 1529
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 15:37

I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.

i.e.

Dim PersonalInfo         


        
6条回答
  •  醉梦人生
    2020-12-09 16:23

    How about using Tagging. Something like:

    Public Enum MyEnum
    Contact
    PersonalInfo
    End Enum
    

    You would have to write the StringValue attribute as:

    Public Class StringValueAttribute
        Inherits Attribute
    
        Public Property Value As String
        Public Sub New(ByVal val As String)
            Value = val
        End Sub
    
    End Class
    

    To get it out:

     Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
        For Each val As [Enum] In [Enum].GetValues(enumType)
            Dim fi As FieldInfo = enumType.GetField(val.ToString())
            Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
            Dim attr As StringValueAttribute = attributes(0)
            If attr.Value = value Then
                Return val
            End If
        Next
        Throw New ArgumentException("The value '" & value & "' is not supported.")
    End Function
    
    Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
        Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
    End Function
    

    And then a call to get the Enum (using string attribute):

    Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
    

    To get the "Attribute" value out (removed handling 'Nothing' for clarity):

      Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
            Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
      End Function
    
      Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
            Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
      End Function
    

    And the call to get the string attribute (using Enum):

    Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
    

提交回复
热议问题