Enum.Parse(), surely a neater way?

前端 未结 5 1958
猫巷女王i
猫巷女王i 2020-12-14 05:32

Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:



        
5条回答
  •  北海茫月
    2020-12-14 06:10

    No, there's no "no-throw" method for this (a la TryParse that some other classes have).

    However, you could easily write your own so as to encapsulate the try-catch logic (or the IsDefined check) in one helper method so it doesn't pollute your app code:

    public static object TryParse(Type enumType, string value, out bool success)
    {
      success = Enum.IsDefined(enumType, value);
      if (success)
      {
        return Enum.Parse(enumType, value);
      }
      return null;
    }
    

提交回复
热议问题