【问题标题】:Convert Enum with [DescriptionAttribute] to Dictionary<string,int> [duplicate]将带有 [DescriptionAttribute] 的枚举转换为 Dictionary<string,int> [重复]
【发布时间】:2014-04-01 09:48:47
【问题描述】:

我有这个枚举

public enum Genders
    {
        [Description("Nữ")]
        Female,
        [Description("Nam")]
        Male
    }

我使用此代码获取每个枚举名称和值并将其保存到字典 结果是

女性:0

男性:1

    accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
                               .Cast<Account.Genders>()
                               .ToDictionary(t => t.ToString(), t => (int)t);

如何修改上述代码以获取每个 Enum 的描述及其值?

像这样。

Nữ : 0

名称:1

【问题讨论】:

    标签: c# dictionary enums


    【解决方案1】:

    根据https://stackoverflow.com/a/2650090/643095的回答,

    string description = Enumerations.GetEnumDescription((MyEnum)value);
    

    其中valueint 枚举值。

    你可以这样使用:

    accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
                                   .Cast<Account.Genders>()
                                   .ToDictionary(t => Enumerations.GetEnumDescription((Genders)t), t => (int)t);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多