zoukankan      html  css  js  c++  java
  • 枚举 字符串--获取描述信息

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    
    namespace ZB.QueueSys.Common.Enum
    {
        public enum QsQueueStatusEnum
        {
            /// <summary>
            /// 启用
            /// </summary>
            [Description("启用")]
            StartUsing = 1,
            /// <summary>
            /// 禁用
            /// </summary>
            [Description("禁用")]
            NoUsing = 0,
        }
    }     
    
    using System.ComponentModel;
    using System.Reflection;
    
    namespace ZB.QueueSys.Common
    {
        public class EnumHelper
        {
            //定义一个用于保存静态变量的实例
            private static EnumHelper instance = null;
            //定义一个保证线程同步的标识
            private static readonly object locker = new object();
            //构造函数为私有,使外界不能创建该类的实例
            private EnumHelper() { }
            public static EnumHelper Instance
            {
                get
                {
                    if (instance == null)
                    {
                        lock (locker)
                        {
                            if (instance == null) instance = new EnumHelper();
                        }
                    }
                    return instance;
                }
            }
    
            public string GetEnumDescription(System.Enum enumValue)
            {
                string value = enumValue.ToString();
                FieldInfo field = enumValue.GetType().GetField(value);
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  //获取描述属性
                if (objs == null || objs.Length == 0)  //当描述属性没有时,直接返回名称
                    return value;
                DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
                return descriptionAttribute.Description;
            }
    
            //扩展方法,必须定义在静态类、静态方法
            //public static string GetDescription(this System.Enum value)
            //{
            //    FieldInfo field = value.GetType().GetField(value.ToString());
    
            //    DescriptionAttribute attribute
            //            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
            //                as DescriptionAttribute;
    
            //    return attribute == null ? value.ToString() : attribute.Description;
            //}
    
        }
    }
    

      

      

    博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!
  • 相关阅读:
    【webpack系列】从零搭建 webpack4+react 脚手架(一)
    js常见的面试题
    java中读取资源文件的方法
    java servlet的域对象
    java 静态资源访问详解
    java servlet简述
    mysql免解压版的配置
    java网络编程
    java单例设计模式
    java多线程及线程安全详解
  • 原文地址:https://www.cnblogs.com/YYkun/p/14523611.html
Copyright © 2011-2022 走看看