Define String ENUM in VB.Net

后端 未结 6 1530
爱一瞬间的悲伤
爱一瞬间的悲伤 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:03

    How can i get this value using ENUM? or anyother way to do it.

    There are three common ways of mapping enum values to strings:

    • Use a Dictionary(Of YourEnumType, String)
    • Decorate the enum values with attributes (e.g. DescriptionAttribute) and fetch them with reflection
    • Use a Switch statement

    The first of these options is probably the simplest, in my view.

    0 讨论(0)
  • 2020-12-09 16:06

    You could just create a new type

    ''' <completionlist cref="Test"/>
    Class Test
    
        Private Key As String
    
        Public Shared ReadOnly Contact  As Test = New Test("Personal Contanct")
        Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")
    
        Private Sub New(key as String)
            Me.Key = key
        End Sub
    
        Public Overrides Function ToString() As String
            Return Me.Key
        End Function
    End Class
    

    and when you use it, it kinda looks like an enum:

    Sub Main
    
        DoSomething(Test.Contact)
        DoSomething(Test.PersonalInfo)
    
    End Sub
    
    Sub DoSomething(test As Test)
        Console.WriteLine(test.ToString())
    End Sub
    

    output:

    Personal Contanct
    Personal Info

    0 讨论(0)
  • 2020-12-09 16:11

    If all you want to do is display the enums in a list or combo, you can use tagging such as

    Private Enum MyEnum
        Select_an_option___
        __ACCOUNTS__
        Invoices0
        Review_Invoice
        __MEETINGS__
        Scheduled_Meetings0
        Open_Meeting
        Cancelled_Meetings0
        Current_Meetings0
    End Enum
    

    Then pull the MyEnum into a string and use Replace (or Regex) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:

    Select an option...
    **ACCOUNTS**
    Invoices
    Review Invoice
    **MEETINGS**
    Scheduled Meetings
    Open Meeting
    Cancelled Meetings
    Current Meetings
    

    (You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice and Open Meeting might be expecting additional input so a text box might be enabled for those selections.)

    When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.

    (The explanation is about 10 times as involved as the actual solution!)

    0 讨论(0)
  • 2020-12-09 16:19

    For non-integer values, Const in a Structure (or Class) can be used instead:

    Structure Test
        Const PersonalInfo = "Personal Info"
        Const Contanct = "Personal Contanct"
    End Structure
    

    or in a Module for direct access without the Test. part:

    Module Test
        Public Const PersonalInfo = "Personal Info"
        Public Const Contanct = "Personal Contanct"
    End Module
    

    In some cases, the variable name can be used as a value:

    Enum Test
        Personal_Info
        Personal_Contanct
    End Enum
    
    Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)
    
    ' or in Visual Studio 2015 and newer:
    Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)
    
    0 讨论(0)
  • 2020-12-09 16:23

    How about using Tagging. Something like:

    Public Enum MyEnum
    <StringValue("Personal Contact")>Contact
    <StringValue("My PersonalInfo")>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)
    
    0 讨论(0)
  • 2020-12-09 16:25

    I know this is an old post put I found a nice solution that worth sharing:

    ''' <summary>
    ''' Gives acces to strings paths that are used often in the application
    ''' </summary>
    Public NotInheritable Class Link        
        Public Const lrAutoSpeed As String          = "scVirtualMaster<.lrAutoSpeed>"
        Public Const eSimpleStatus As String        = "scMachineControl<.eSimpleStatus>"
        Public Const xLivebitHMI As String          = "scMachineControl<.xLivebitHMI>"      
        Public Const xChangeCycleActive As String   = "scMachineControl<.xChangeCycleActive>"
    
    End Class
    

    Usage:

    'Can be anywhere in you applicaiton:
    Link.xChangeCycleActive
    

    This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.

    Also visual studio shows the string attributes right after you type "Link" just like if it is a regular Enum

    0 讨论(0)
提交回复
热议问题