[英]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
当我调用Convert.ChangeType
,系统会因无法从String转换为Category而抛出异常。 怎么做转换? 也许我需要为我的类型实现任何转换器?
为此使用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));
}
.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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.