如何通过枚举名称和值名称获取未知枚举的值?

时间:2012-09-04 19:40:00

标签: c# enums

很抱歉提出这个问题,但我找不到适合这项任务的解决方案:

我有一个Enum,名为“myEnum”(该功能不知道MyEnum) 我需要获取myEnum值的int值

例:
程序员将其枚举命名为“myEnum”:

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

我的功能应该做到以下几点:      通过字符串

获取“myEnum”的“foo”值

功能应该打开:

 public int GetValueOf(string EnumName, string EnumConst)
 {

 }

所以当程序员A打开它时:

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

它应该返回1

当程序员B有一个名为“mySpace”的枚举时,想要返回值为5的“bar”

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

应该返回5

我该怎么做?

4 个答案:

答案 0 :(得分:27)

您可以使用Enum.Parse执行此操作,但您需要Enum类型的完全限定类型名称,即:"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);
}

另请注意,这会使用Convert.ToInt32而不是强制转换。这将处理具有非Int32的基础类型的枚举值。但是,如果您的枚举的基础值超出OverflowException的范围(例如:如果值为> Int32则为ul),则仍会抛出int.MaxValue

答案 1 :(得分:7)

请尝试

int result = (int) Enum.Parse(Type.GetType(EnumName), EnumConst);

答案 2 :(得分:2)

我想你试图从字符串值(它的名字)中实现枚举,然后我会建议你get it members via reflection然后进行比较。

请注意反思adds a bit of overhead

答案 3 :(得分:2)

我不清楚枚举类型的名称是否必须指定为字符串。

您需要使用Enum.TryParse来获取Enum的值。结合通用方法,您可以执行以下操作:

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;
}

要打电话给它:

int? result = GetValueOf<myEnum>("bar");
if (result.HasValue)
{
    //work with value here.
}