Convert.ChangeType如何从String转换为Enum

Mix*_*xer 27 c# enums converter

  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
Run Code Online (Sandbox Code Playgroud)

当我调用时Convert.ChangeType,系统会因无法从String转换为Category而抛出异常.怎么做转换?也许我需要为我的类型实现任何转换器?

Ton*_*ony 69

为此使用Enum.Parse方法.

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));
}
Run Code Online (Sandbox Code Playgroud)

  • `(T)Enum.Parse(typeof(T), value, true); // 忽略大小写:true。` (2认同)

tre*_*urt 8

.Net核心版:

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));
}
Run Code Online (Sandbox Code Playgroud)