【C#】枚举与Description配合使用实例

实现方式一

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());

参考文章:CSDN论坛CSDN博客

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值