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

前端 未结 7 870
深忆病人
深忆病人 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:42

    To parse the age:

    Age age;
    if (Enum.TryParse(typeof(Age), "New_Born", out age))
      MessageBox.Show("Defined");  // Defined for "New_Born, 1, 4 , 8, 12"
    

    To see if it is defined:

    if (Enum.IsDefined(typeof(Age), "New_Born"))
       MessageBox.Show("Defined");
    

    Depending on how you plan to use the Age enum, flags may not be the right thing. As you probably know, [Flags] indicates you want to allow multiple values (as in a bit mask). IsDefined will return false for Age.Toddler | Age.Preschool because it has multiple values.

    0 讨论(0)
提交回复
热议问题