C# EnumHelper Enum的值,Description,ToString()的相互转换,
分享于 点击 25057 次 点评:281
C# EnumHelper Enum的值,Description,ToString()的相互转换,
首先定义枚举类型,
/// <summary>
/// 板块
/// </summary>
public enum Plate
{
[Description("所有市场")]
All = 0,
[Description("沪深300")]
HS300 = 1,
[Description("创业板")]
CYB = 2,
[Description("上证50")]
SZ50 = 3,
[Description("中小板")]
ZXB = 4,
[Description("中证500")]
ZZ500 = 5,
[Description("包括指数")]
BKZS = 6,
}
接下来是Helper类
public static class EnumHelper
{
/// <summary>
/// 获取枚举值的Description
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static string GetDescription<T>(this T value) where T : struct
{
string result = value.ToString();
Type type = typeof(T);
FieldInfo info = type.GetField(value.ToString());
var attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attributes != null && attributes.FirstOrDefault() != null)
{
result = (attributes.First() as DescriptionAttribute).Description;
}
return result;
}
/// <summary>
/// 根据Description获取枚举值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T GetValueByDescription<T>(this string description) where T : struct
{
Type type = typeof(T);
foreach (var field in type.GetFields())
{
if (field.Name == description)
{
return (T)field.GetValue(null);
}
var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attributes != null && attributes.FirstOrDefault() != null)
{
if (attributes.First().Description == description)
{
return (T)field.GetValue(null);
}
}
}
throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
}
/// <summary>
/// 获取string获取枚举值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T GetValue<T>(this string value) where T : struct
{
T result;
if (Enum.TryParse(value, true, out result))
{
return result;
}
throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", value), "Value");
}
}
接下来贴上我的测试代码
string descprition = Plate.HS300.GetDescription(); //=沪深300
string value = Plate.HS300.ToString(); // =HS300
Plate plate1 = "HS300".GetValue<Plate>(); //=Plate.沪深300
Plate plate = "沪深300".GetValueByDescription<Plate>();//=Plate.沪深300
搞定啦。
相关文章
- 暂无相关文章
用户点评