实现方式一
private void btnDescription_Click(object sender, EventArgs e)
{
AlignStyle alst = AlignStyle.top;
Type t = alst.GetType();
FieldInfo info = t.GetField(Enum.GetName(t, alst));
DescriptionAttribute description = (DescriptionAttribute)Attribute.GetCustomAttribute(info,typeof(DescriptionAttribute));
MessageBox.Show(description.Description);
}
public enum AlignStyle
{
[Description("不对齐")]
none,
[Description("上对齐")]
top,
[Description("下对齐")]
bottom,
[Description("居中")]
center
}
打印结果:
实现方式二
为枚举定义ToDescription方法。C#中的枚举是不支持定义方法的。我们可以为其做一个扩展方法,扩展方法需要一个静态类,参数前要加this ,同时也指定了被扩展的对象,调用时可使用扩展对像的实例调用,也可以使用该静态类来调用。扩展类如下:
public static class Extension
{
public static string ToDescription(this AlignStyle myEnum)
{
Type type = typeof(AlignStyle);
FieldInfo info = type.GetField(myEnum.ToString());
DescriptionAttribute descriptionAttribute = info.GetCustomAttributes(typeof(DescriptionAttribute), true)[0] as DescriptionAttribute;
if (descriptionAttribute != null)
return descriptionAttribute.Description;
else
return type.ToString();
}
}
这样AlignStyle就多了一个ToDescription的方法,返回的值就是对应的特性值。调用代码:
AlignStyle alst = AlignStyle.top;
MessageBox.Show(alst.ToDescription());