Search for a string in Enum and return the Enum

后端 未结 12 2225
礼貌的吻别
礼貌的吻别 2020-11-28 19:13

I have an enumeration:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

and I have a s

12条回答
  •  悲&欢浪女
    2020-11-28 19:41

    One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here

    With this you can define your enumerations as classes (the examples are in vb.net):

    < StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)

    Private Sub New(ByVal StrValue As String)
      MyBase.New(StrValue)   
    End Sub
    
    < Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")   
    
    < Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")   
    

    End Class

    And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

    I've been using this for a long time now and it makes the code more clear in intent.

提交回复
热议问题