• C#获取枚举描述代码


    public class MusterEnum
        {
            /// 获取枚举的描述信息
            /// </summary>
            /// <param name="e">传入枚举对象</param>
            /// <returns>得到对应描述信息</returns>
            public String GetEnumDesc(Enum e)
            {
                FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
                if (EnumInfo == null)
                {
                    return "";
                }
                DescriptionAttribute[] EnumAttributes
                    = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (EnumAttributes.Length > 0)
                {
                    return EnumAttributes[0].Description;
                }
                return e.ToString();
            }
    
            /// <summary>
            /// 将含有描述信息的枚举绑定到列表控件中
            /// </summary>
            /// <param name="listControl"></param>
            /// <param name="enumType"></param>
            private Dictionary<string, string> BindDesEnumToListControl(System.Type enumType)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (object enumValue in Enum.GetValues(enumType))
                {
                    Enum e = (Enum)enumValue;
                    dic.Add(((int)enumValue).ToString(), GetEnumDesc(e));
                }
                return dic;
            }
    }

    还有一个是根据传入的枚举的数字索引直接获取

            public static string GetEnumDesc<T>(Object obj)
            {
                obj = (T)obj;
                if (obj == null) throw new ArgumentNullException("参数不能为null");
                if (!obj.GetType().IsEnum) throw new Exception("参数类型不正确");
                FieldInfo fieldinfo = obj.GetType().GetField(obj.ToString());
    
                string str = string.Empty;
                Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs != null && objs.Length != 0)
                {
                    DescriptionAttribute des = (DescriptionAttribute)objs[0];
                    str = des.Description;
                }
                return str;
            }
  • 相关阅读:
    laravel常用函数大全Helper
    laravel查询语句指定索引(mysql强制索引)
    laravel-admin后台系统开发
    ES搜索引擎详解
    怎么查看当前的git分支是基于哪个分支创建的
    laravel中使用offsetSet
    laragon安装新的php版本
    Laravel collect妙用
    composer install file could not be downloaded (HTTP/1.1 405 Not Allowed)
    garphql
  • 原文地址:https://www.cnblogs.com/subendong/p/2879636.html
Copyright © 2020-2023  润新知