Search for a string in Enum and return the Enum

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

    Given the latest and greatest changes to .NET (+ Core) and C# 7, here is the best solution:

    var ignoreCase = true;
    Enum.TryParse("red", ignoreCase , out MyColours colour);
    

    colour variable can be used within the scope of Enum.TryParse

提交回复
热议问题