Validate Enum Values

前端 未结 11 1016
你的背包
你的背包 2020-11-30 09:43

I need to validate an integer to know if is a valid enum value.

What is the best way to do this in C#?

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 10:22

    You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!

    IsDefined is fine for most scenarios, you could start with:

    public static bool TryParseEnum(this int enumValue, out TEnum retVal)
    {
     retVal = default(TEnum);
     bool success = Enum.IsDefined(typeof(TEnum), enumValue);
     if (success)
     {
      retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
     }
     return success;
    }
    

    (Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)

提交回复
热议问题