简体   繁体   English

从字符串中查找枚举类型并以列表形式返回枚举值<string>

[英]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. 我想创建一个API,它将以字符串形式发送枚举名称,并且应该以字符串列表形式返回枚举值。 For eg my project contains n number of enums 例如,我的项目包含n个枚举

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 我的API调用应该像这样

List<string> GetEnumValuse(string enumName)

So a call could be like this GetEnumValues("WeekDays") which should return List of enum values. 因此,调用可能像这样的GetEnumValues("WeekDays") ,它应该返回枚举值列表。 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. 我关心的是我应该使用switch ... case并找出项目中的所有枚举,而是有一种方法可以解析字符串以枚举并查找是否存在Weekdays或Colors的枚举类型,这样我就不会不需要使用switch ...案例。

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. 您确实确实需要使用名称空间(在示例中为ConsoleApplication1 )进行反射,以使用此方法找到您的枚举,但这是迄今为止我能想到的最简洁的方法。

This solution first searchs in current namespace if enum is not found then it performs deep search within current AppDomain. 如果未找到枚举,此解决方案首先在当前名称空间中搜索,然后在当前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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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