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

Dan*_*arr 17 c# enums

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

我有一个枚举,名为"myEnum"(函数不知道MyEnum)我需要获取myEnum值的int值

示例:
程序员将其枚举命名为"myEnum":

 public enum myEnum
 {
     foo = 1,
     bar = 2,
 }
Run Code Online (Sandbox Code Playgroud)

我的函数应该执行以下操作:通过字符串获取"myEnum"的"foo"值

功能应该打开:

 public int GetValueOf(string EnumName, string EnumConst)
 {

 }
Run Code Online (Sandbox Code Playgroud)

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

 int a = GetValueOf("myEnum","foo");
Run Code Online (Sandbox Code Playgroud)

它应该返回1

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

int a = GetValueOf("mySpace","bar")
Run Code Online (Sandbox Code Playgroud)

应该返回5

我怎样才能做到这一点?

Ree*_*sey 29

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

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


pet*_*kyy 7

请试试

int result = (int) Enum.Parse(Type.GetType(EnumName), EnumConst);
Run Code Online (Sandbox Code Playgroud)

  • @ReedCopsey是的,好评.要修复你,可以改用Convert.ToInt32. (2认同)