how to check if string value is in the Enum list?

前端 未结 7 934
深忆病人
深忆病人 2021-01-30 05:15

In my query string, I have an age variable ?age=New_Born.

Is there a way I can check if this string value New_Born is in my Enum list

7条回答
  •  灰色年华
    2021-01-30 05:39

    You should use Enum.TryParse to achive your goal

    This is a example:

    [Flags]
    private enum TestEnum
    {
        Value1 = 1,
        Value2 = 2
    }
    
    static void Main(string[] args)
    {
        var enumName = "Value1";
        TestEnum enumValue;
    
        if (!TestEnum.TryParse(enumName, out enumValue))
        {
            throw new Exception("Wrong enum value");
        }
    
        // enumValue contains parsed value
    }
    

提交回复
热议问题