简体   繁体   中英

Convert.ChangeType How to convert from String to Enum

  public static T Convert<T>(String value)
  {
    return (T)Convert.ChangeType(value, typeof(T));
  }

   public enum Category 
   {
       Empty,
       Name,
       City,
       Country
   }

  Category cat=Convert<Category>("1");//Name=1

When I call Convert.ChangeType , the system throws an exception on the impossibility of conversion from String to Category. How to do the conversion? Maybe I need to implement any converter for my type?

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));
}

.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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM