Enum from string, int, etc

后端 未结 7 941
伪装坚强ぢ
伪装坚强ぢ 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:14

    You can do:

    public static class EnumExtensions
    {
        public static Enum FromInt32(this Enum obj, Int32 value)
        {
            return (Enum)((Object)(value));
        }
    
        public static Enum FromString(this Enum obj, String value)
        {
            return (Enum)Enum.Parse(obj.GetType(), value);
        }
    }
    

    Or:

    public static class Int32Extensions
    {
        public static Enum ToEnum(this Int32 obj)
        {
            return (Enum)((Object)(obj));
        }
    }
    
    public static class StringExtensions
    {
        public static Enum ToEnum(this Enum obj, String value)
        {
            return (Enum)Enum.Parse(obj.GetType(), value);
        }
    }
    
    0 讨论(0)
提交回复
热议问题