how to get value of an unknown enum by name of enu

2020-02-06 05:09发布

sorry for asking this question but i didn't found the right solution for this task:

I've got a Enum, which is named "myEnum" (MyEnum isn't known by the function) I Need to get the int value of a Value of myEnum

Example:
A Programmer named its enum "myEnum":

 public enum myEnum
 {
     foo = 1,
     bar = 2,
 }

my function should do the following: Get the Value of "foo" of "myEnum" by string

function should opened by:

 public int GetValueOf(string EnumName, string EnumConst)
 {

 }

so when Programmer A opens it by :

 int a = GetValueOf("myEnum","foo");

it should return 1

and when Programmer B has an Enum named "mySpace", wants to return "bar" with Value 5

int a = GetValueOf("mySpace","bar")

should return 5

how can i do this?

标签: c# enums
4条回答
劫难
2楼-- · 2020-02-06 05:50

Please try

int result = (int) Enum.Parse(Type.GetType(EnumName), EnumConst);
查看更多
何必那么认真
3楼-- · 2020-02-06 05:54

I suppose you're trying to instance the enum from the string value (it's name) then I'll suggest you to get it members via reflection and then compare.

Please be aware reflection adds a bit of overhead.

查看更多
够拽才男人
4楼-- · 2020-02-06 05:55

It's not clear to me if the name of the enum type must be specified as a string.

You need to use Enum.TryParse to get the value of the Enum. In combination with a generic method, you could do something like this:

public int? GetValueOf<T>(string EnumConst) where T : struct
{
    int? result = null;

    T temp = default(T);
    if (Enum.TryParse<T>(EnumConst, out temp))
    {
        result = Convert.ToInt32(temp);
    }

    return result;
}

To call it use this:

int? result = GetValueOf<myEnum>("bar");
if (result.HasValue)
{
    //work with value here.
}
查看更多
聊天终结者
5楼-- · 2020-02-06 05:59

You can use Enum.Parse to do this, but you'd need the fully qualified type name of the Enum type, ie: "SomeNamespace.myEnum":

public static int GetValueOf(string enumName, string enumConst)
{
    Type enumType = Type.GetType(enumName);
    if (enumType == null)
    {
        throw new ArgumentException("Specified enum type could not be found", "enumName");
    }

    object value = Enum.Parse(enumType, enumConst);
    return Convert.ToInt32(value);
}

Also note that this uses Convert.ToInt32 instead of a cast. This will handle enum values with underlying types which are not Int32. This will still throw an OverflowException, however, if your enum has an underlying value outside of the range of an Int32 (ie: if it's a ulong as the value is >int.MaxValue).

查看更多
登录 后发表回答