Convert.ChangeType如何将字符串转换为枚举 [英] Convert.ChangeType How to convert from String to Enum
本文介绍了Convert.ChangeType如何将字符串转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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转换为类别引发异常。
如何做转换?
也许我需要为我的类型实现任何转换器?
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?
推荐答案
使用 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));
}
这篇关于Convert.ChangeType如何将字符串转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文