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
,系统略知转换不可能从字符串类别的异常。
如何进行转换? ?
也许我需要实现我的任何类型转换
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~~V 方法这一点。
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屋!
查看全文