Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c# - how to get value of an unknown enum by name of enum and name of value?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...