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;
}
}