Enum.TryParse returns true for any numeric values

后端 未结 2 1403
轮回少年
轮回少年 2020-12-08 12:48

I\'m running into a behavior I wasn\'t expecting when using Enum.TryParse.

If I have an enum:

public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}


        
相关标签:
2条回答
  • 2020-12-08 13:29

    Use it like this

    bool result = Enum.TryParse("1234", out MyEnum outputEnum) && Enum.IsDefined(typeof(MyEnum), outputEnum);
    

    The value of result will be false but the value of outputEnum is still 1234

    0 讨论(0)
  • 2020-12-08 13:36

    This behavior is by design.

    The documentation says:

    . If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

    Call Enum.IsDefined to veryify that the value you parsed actually exists in this particular enum.

    If you're dealing with [Flags] enums (bitmasks), it'll get more complicated.

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