Search for a string in Enum and return the Enum

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

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

    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.Parse(stringValue); 
    

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

提交回复
热议问题