如何使用描述属性将枚举转换为字典? [英] How to cast Enum with Description attribute to dictionary?

查看:220
本文介绍了如何使用描述属性将枚举转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此问题,并且最好使用此答案以及答案获取枚举属性,如何将枚举转换为一个字典,其中 Key 是枚举值本身和是描述属性?

Based on this question, and preferably using this answer along with this answer to get enum attributes, how is it possible to cast the enum to a dictionary where Key is the enum value itself and Value is the description attribute?

推荐答案

给定 GetAttributeOfType& T>()扩展方法你可以简单地做:

Given the GetAttributeOfType<T>() extension method you can simply do:

var dic = Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>())

如果您直接要求描述的值:

If you directly want the Description in the value:

var dic = Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)

这篇关于如何使用描述属性将枚举转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆