Как получить все значения Enum, присвоенные моей модели, возвращаются в виде списка в c #? - PullRequest
0 голосов
/ 17 января 2019

Я планировал заполнить раскрывающийся список моей страны с помощью Enum. Так что мне нужно описание значения Enum и это значение индекса. Мои условия:

  1. Я хочу все описание Enum Value со значением индекса.
  2. Мне не нужно только значение Enum, мне нужно описание и индекс.

Мой Enum:

public enum CountryListEnum
    {
        [Description("United Kingdom")]
        UnitedKingdom = 0,
        [Description("United States")]
        UnitedStates = 1,
        [Description("Afghanistan")]
        Afghanistan = 2,
        [Description("Albania")]
        Albania = 3,
    }

Моя модель:

public class CountryModel
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }

Ответы [ 3 ]

0 голосов
/ 17 января 2019

Чтобы получить значение индекса, вы можете просто привести перечисление к int. Получение атрибута description немного сложнее. Может быть, что-то вроде этого

public enum CountryListEnum
{
    [Description("United Kingdom")]
    UnitedKingdom = 0,
    [Description("United States")]
    UnitedStates = 1,
    [Description("Afghanistan")]
    Afghanistan = 2,
    [Description("Albania")]
    Albania = 3,
}

static void Main(string[] args)
{
    foreach (var country in Enum.GetValues(typeof(CountryListEnum)).Cast<CountryListEnum>())
    {
        Console.WriteLine($"Index: {(int)country}");
        Console.WriteLine($"Description: {GetDescription(country)}");
    }
}

public static string GetDescription(Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        System.Reflection.FieldInfo field = type.GetField(name);
        if (field != null)
        {
            if (Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) is DescriptionAttribute attr)
            {
                return attr.Description;
            }
        }
    }
    return null;
}
0 голосов
/ 17 января 2019

Я думаю, это то, что вы ищете.

var model = new List<CountryModel>();
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
    model.Add(new CountryModel
    {
        CountryId = (int)item,
        CountryName = ((DescriptionAttribute)item.GetType().GetField(item.ToString()).GetCustomAttribute(typeof(DescriptionAttribute), false)).Description
    });
}
0 голосов
/ 17 января 2019

Я думаю, что это должно помочь вам с реализацией.

        foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
        {
            CountryModel myModel = new CountryModel();

            myModel.CountryId = item.GetHashCode();
            myModel.CountryName = item.ToString();
        }

Редактировать

Как указали другие, приведенное выше не получит описание.Вот обновление о том, как реализовать повторную попытку атрибута description.

        foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
        {
            CountryModel myModel = new CountryModel();

            myModel.CountryId = item.GetHashCode();

            var type = typeof(CountryListEnum);
            var memInfo = type.GetMember(item.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            var description = ((DescriptionAttribute)attributes[0]).Description;

            myModel.CountryName = description;
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...