Enum from string, int, etc

后端 未结 7 1036
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 07:23

Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt(), ToString()

7条回答
  •  滥情空心
    2021-01-17 08:11

    I would avoid polluting int or string with extension methods for enums, instead a good old fashioned static helper class might be in order.

    public static class EnumHelper
    {
       public static T FromInt(int value)
       {
           return (T)value;
       }
    
      public static T FromString(string value)
      {
         return (T) Enum.Parse(typeof(T),value);
      }
    }
    

提交回复
热议问题