Search for a string in Enum and return the Enum

后端 未结 12 2166
礼貌的吻别
礼貌的吻别 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:40

    All you need is Enum.Parse.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 19:43
    (MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
    (int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
    
    0 讨论(0)
  • 2020-11-28 19:43

    You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>

    The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse - instead you end up writing something like this in your code:

    MyColours colour = Enum<MyColours>.Parse(stringValue); 
    

    Or check out some of the comments in the same post which talk about using an extension method to achieve similar.

    0 讨论(0)
  • 2020-11-28 19:44
    var color =  Enum.Parse<Colors>("Green");
    
    0 讨论(0)
  • 2020-11-28 19:51

    You can cast the int to an enum

    (MyColour)2
    

    There is also the option of Enum.Parse

    (MyColour)Enum.Parse(typeof(MyColour), "Red")
    
    0 讨论(0)
提交回复
热议问题