獲取列舉及屬性的DescriptionAttribute值
阿新 • • 發佈:2019-01-08
1.列舉
System.Array values = Enum.GetValues(typeof(EnumType));
foreach (EnumType type in values)
{
this.cmbType.Properties.Items.Add(GetEnumDescription(type));
}
/// <summary> /// 獲取列舉類子項描述資訊 /// </summary> /// <param name="enumItem">列舉類子項</param> public static string GetEnumDescription(Enum enumItem) { Type enumType = enumItem.GetType(); string sName = Enum.GetName(enumType, enumItem); if (sName == null) { return null; } FieldInfo fieldinfo = enumType.GetField(sName); Object[] attrs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs == null || attrs.Length == 0) { return sName; } else { DescriptionAttribute descAttr = (DescriptionAttribute)attrs[0]; return descAttr.Description; } }
2.屬性
var ent = new Ent(); foreach (var item in ent.GetType().GetProperties()) { var v = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false); var descriptionName = v[0].Description; item.SetValue(ent,descriptionName+":1"); }
private class EnumHelper { /// <summary> /// 獲取列舉值上的Description特性的說明 /// </summary> /// <typeparam name="T">列舉型別</typeparam> /// <param name="obj">列舉值</param> /// <returns>特性的說明</returns> public static string GetEnumDescription<T>(T obj) { var type = obj.GetType(); FieldInfo field = type.GetField(Enum.GetName(type, obj)); DescriptionAttribute descAttr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (descAttr == null) { return string.Empty; } return descAttr.Description; } }