Convert.ChangeType How to convert from String to Enum

后端 未结 2 1483
孤独总比滥情好
孤独总比滥情好 2020-12-29 20:47
  public static T Convert(String value)
  {
    return (T)Convert.ChangeType(value, typeof(T));
  }

   public enum Category 
   {
       Empty,
       Name         


        
相关标签:
2条回答
  • 2020-12-29 21:19

    Use Enum.Parse method for this.

    public static T Convert<T>(String value)
    {
        if (typeof(T).IsEnum)
           return (T)Enum.Parse(typeof(T), value);
    
        return (T)Convert.ChangeType(value, typeof(T));
    }
    
    0 讨论(0)
  • 2020-12-29 21:21

    .Net Core version :

    public static T Convert<T>(string value)
    {
        if (typeof(T).GetTypeInfo().IsEnum)
            return (T)Enum.Parse(typeof(T), value);
    
        return (T)System.Convert.ChangeType(value, typeof(T));
    }
    
    0 讨论(0)
提交回复
热议问题