首页 技术 正文
技术 2022年11月11日
0 收藏 665 点赞 4,460 浏览 1368 个字

枚举中的Descript()描述值,以及枚举值是一种一一对应的关系。我们可以获取其描述值和枚举值,存放到字典中,

在实际的使用中我们就可以轻松的根据枚举值来获取其描述值,也可以通过枚举的描述值来获取其枚举值。

根据枚举值来获取其描述值如下:

/// <summary>
        /// 根据枚举值来获取描述信息
        /// </summary>
        /// <param name=”e”>枚举值</param>
        /// <returns></returns>
        public static string GetEnumDesc(Enum e)
        {
            DescriptionAttribute[] descAttribute = (DescriptionAttribute[])e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return descAttribute == null || descAttribute.Length == 0 ? string.Empty : descAttribute[0].Description;
        }

但是这种方法是比较单一的,只能根据一个枚举值来获取一个描述信息。

以下便可以实现获取所有的枚举值和秒速信息

/// <summary>

/// 根据枚举类型来获取枚举值和枚举描述信息

/// </summary>

/// <typeparam name=”T”></typeparam>

/// <returns></returns>

public static Dictionary<int, string> GetValueAndDesc<T>()         {

Dictionary<int, string> dic = new Dictionary<int, string>();

try

{

foreach (FieldInfo item in typeof(T).GetFields())

{

if (item.FieldType.IsEnum)

{

int key = (int)typeof(T).InvokeMember(item.Name, BindingFlags.GetField, null, null, null);

DescriptionAttribute[] descs = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false);

if (descs.Length > 0 && !dic.ContainsKey(key))

{

dic.Add(key, descs[0].Description);

}

}

}

}

catch (Exception)

{                // throw;             }

return dic;

}

这样之后我们可以轻松的通过键值对来轻松的获取我们先要的值或者描述信息。

————————哇!我这都三年5个月的博客龄了,不过一直没有写博客,希望通过我们分享,能给有需要的朋友们带来帮助————–

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297