Search for a string in Enum and return the Enum

后端 未结 12 2240
礼貌的吻别
礼貌的吻别 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 20:02

    I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

    public MyColours GetColours(string colour)
    {  
       foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
       if (mc.ToString() == surveySystem) 
          return mc;
    
       return MyColors.Default;
    }
    

提交回复
热议问题