简体   繁体   中英

Convert an Enum to a List<object>

First, to avoid the knee-jerk "This is a duplicate" statements: There are plenty of questions on SO about serializing enums. But none (that I have found) deal with enums that have descriptions, or that try to convert an Enum to a specific object. (If you can find one that I missed, then I will accept that this is a duplicate.)

Given an enum that looks something like this:

public enum OptionType
{
    [Description("Option A")]
    OptionA = 1,

    [Description("Option B")]
    OptionB = 2,

    Description("Option C")]
    OptionC= 3,
    }

I would like to convert this into a JSON string that looks like this:

[
    { "Id": "1", "Description": "Option A"},
    { "Id": "2", "Description": "Option B"},
    { "Id": "3", "Description": "Option C"}
]

I have these two classes:

public class EnumList
{
    public List<EnumNameValue> EnumNamesValues { get; set; }
}

public class EnumNameValue
{
    public int Id { get; set; }
    public string Description { get; set; }
}

And I have a calling method that looks like this:

EnumList enumList = EnumSerializer.EnumToJson<OptionType>();

And finally (and this is where I need help):

public static class EnumSerializer
{
    public static EnumList EnumToJson<T>() where T : Enum
    {
        Type enumType = typeof(T);                                 // <--- WORKS!!
        Enum thisEnum1 = (T)Activator.CreateInstance(enumType);    // <--- DOES NOT WORK
        Enum thisEnum2 = (Enum)Activator.CreateInstance(enumType); // <--- DOES NOT WORK

        // If I can get this far, I *THINK* I can figure it out from here
   
    }
}

I already have an Enum extension that gets the Description, so I don't need help with that. The problem I'm having is that both thisEnum1 and thisEnum2 end up having a value of 0

在此处输入图像描述

( DistrictType is the real name of the Enum.)

How do I get an actual instance of the enum that I can then loop over?

public static class EnumSerializer
{
    public static EnumList EnumToJson<T>() where T : struct, Enum
    {
        var type = typeof(T);
        var values = Enum.GetValues<T>()
            .Select(x => new EnumNameValue
            {
                Id = (int)(object)x,
                Description = type.GetField(x.ToString())
                    .GetCustomAttribute<DescriptionAttribute>().Description
            });

        return new EnumList { EnumNamesValues = values.ToList() };
    }
}

Working example

Enum.GetValues iterates over the constants declared in your enum.

Of course you can swap out the Description part with your extension method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM