C# 如何将具有Description属性的枚举强制转换为dictionary?

C# 如何将具有Description属性的枚举强制转换为dictionary?,c#,enums,C#,Enums,基于此,最好将其与此一起使用,如何将枚举强制转换到字典中,其中Key是枚举值本身,而value是描述属性?给定GetAttributeOfType()扩展方法,您可以简单地执行以下操作: var dic = Enum.GetValues(typeof(SomeEnum)) .Cast<SomeEnum>() .ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>()) var

基于此,最好将其与此一起使用,如何将枚举强制转换到字典中,其中
Key
是枚举值本身,而
value
是描述属性?

给定
GetAttributeOfType()
扩展方法,您可以简单地执行以下操作:

var dic = Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>())
var dic=Enum.GetValues(typeof(SomeEnum))
.Cast()
.ToDictionary(k=>k,v=>v.GetAttributeOfType())
如果直接希望在值中显示说明:

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