简体   繁体   中英

Find Enum Type from string and return enum values as List<string>

I want to create an API which will send a enum name as string and it should return enum value as list of string. For eg my project contains n number of enums

enum WeekDays{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday }

another enum could be

enum Colors{ Red,Green,Blue,Yellow }

My API call should be like this

List<string> GetEnumValuse(string enumName)

So a call could be like this GetEnumValues("WeekDays") which should return List of enum values. My concern is I should use a switch...case and figure out all enums in the project, Instead is there a method where I could parse the string to enum and find whether there is an enum type of WeekDays or Colors so that I don't need to use switch...case.

If you have the fully qualified name of you enum (ie namespace + class name), you can get your result like this :

public IEnumerable<string> GetEnumValues(string enumName)
{
    foreach (var value in Enum.GetValues(Type.GetType(enumName)))
    {
        yield return value.ToString();
    }
}

which is called like that:

IEnumerable<string> enumValues = GetEnumValues("ConsoleApplication1.Colors");

Basically you get the enum values from reflection, and then return their name as a string.

You really do need the namespace (in the example, it is ConsoleApplication1 ) for the reflection to find your enum with this method, but it's by far the cleanest way I could come up with.

This solution first searchs in current namespace if enum is not found then it performs deep search within current AppDomain.

public Type DeepSearchType(string name)
{
    if(string.IsNullOrWhiteSpace(name))
       return null;

    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
    {
        foreach (Type t in a.GetTypes())
        {
            if(t.Name.ToUpper() == name.ToUpper())
               return t;
        }
    }

    return null;
}

public List<string> GetEnumValues(string enumName)
{
    List<string> result = null;

    var enumType = Type.GetType(enumName);

    if(enumType == null)
       enumType = DeepSearchType(enumName);

    if(enumType != null)
    {
        result = new List<string>();

        var enumValues = Enum.GetValues(enumType);

        foreach(var val in enumValues)
            result.Add(val.ToString());
    }

    return result;
}

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