如何将具有描述属性的枚举转换为字典?

How to cast Enum with Description attribute to dictionary?

基于此 question, and preferably using this answer along with this answer to get enum attributes,如何将枚举转换为字典,其中 Key 是枚举值本身,Value 是描述属性?

鉴于 GetAttributeOfType<T>() 扩展方法,您可以简单地执行以下操作:

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

如果直接想要值中的Description:

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