C# 转换枚举为字典

FieldInfo[] fields = typeof(EnumToDictionaryEnum)
    .GetFields(BindingFlags.Static | BindingFlags.Public)
    ?? Array.Empty<FieldInfo>();

var dictionary = fields.ToDictionary(k => k.Name, v => (int)v.GetValue(null));

var dictionary2 = Enum.GetValues(typeof(EnumToDictionaryEnum))
    .Cast<EnumToDictionaryEnum>()
    .ToDictionary(k => k.ToString(), v => (int)v);

示例代码

EnumToDictionaryTestDemo

posted @ 2022-03-03 19:31  Lulus  阅读(497)  评论(0编辑  收藏  举报