C# Enum 获取枚举属性

Enum使用 获取枚举属性

注意:扩展方法必须定义为静态类,静态方法中。

public enum EnumPatientSource
    {
        [Description("住院")]
        INHOSPITAL = -1,

        [Description("门诊")]
        OUTPATIENT = 0,
    }

    public static class EnumHelper
    {
        public static string ToDescription(this Enum val)
        {
            var type = val.GetType();
            var memberInfo = type.GetMember(val.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            //如果没有定义描述,就把当前枚举值的对应名称返回
            if (attributes == null || attributes.Length != 1) return val.ToString();

            return (attributes.Single() as DescriptionAttribute).Description;
        }
    }

测试使用如下所示:

 private void button2_Click(object sender, EventArgs e)
        {
            StringBuilder buf = new StringBuilder(1024);
            buf.AppendLine("枚举==" + EnumPatientSource.INHOSPITAL);
            buf.AppendLine("枚举属性==" + EnumHelper.ToDescription(EnumPatientSource.INHOSPITAL));
            MessageBox.Show(buf.ToString());
        }

猜你喜欢

转载自www.cnblogs.com/YYkun/p/10383329.html