zoukankan      html  css  js  c++  java
  • 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());
            }
    

  • 相关阅读:
    函数及习题
    数组和集合
    数组和集合实例
    普通集合和泛型集合的区别,哈希表和字典表的区别,队列和堆栈的区别以及堆和栈的区别。
    c#时间表示
    c#正则表达式
    js正则实例
    习题实例
    c#数据类型
    简单控件
  • 原文地址:https://www.cnblogs.com/YYkun/p/10383329.html
Copyright © 2011-2022 走看看