Convert.ChangeType如何从String转换为Enum

public static T Convert(String value) { return (T)Convert.ChangeType(value, typeof(T)); } public enum Category { Empty, Name, City, Country } Category cat=Convert("1");//Name=1 

当我调用Convert.ChangeType ,系统会因无法从String转换为Category而抛出exception。 如何进行转换? 也许我需要为我的类型实现任何转换器?

为此使用Enum.Parse方法。

 public static T Convert(String value) { if (typeof(T).IsEnum) return (T)Enum.Parse(typeof(T), value); return (T)Convert.ChangeType(value, typeof(T)); } 

.Net核心版:

 public static T Convert(string value) { if (typeof(T).GetTypeInfo().IsEnum) return (T)Enum.Parse(typeof(T), value); return (T)System.Convert.ChangeType(value, typeof(T)); }