如何通过枚举名称和值的名称获取未知枚举的值? [英] how to get value of an unknown enum by name of enum and name of value?

查看:218
本文介绍了如何通过枚举名称和值的名称获取未知枚举的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个问题,我没有找到正确的解决方案,但我没有找到正确的解决方案:

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

我有一个名为myEnum的枚举MyEnum不被函数所知)
我需要获取myEnum值的int值

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

示例:

A程序员命名其枚举myEnum:

Example:
A Programmer named its enum "myEnum":

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

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

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

函数应该打开:

 public int GetValueOf(string EnumName, string EnumConst)
 {

 }

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

so when Programmer A opens it by :

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

它应该返回1

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

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

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

应该返回5

我可以这样做吗?

推荐答案

您可以使用 Enum.Parse 执行此操作,但您需要Enum类型的完全限定类型名称,即:SomeNamespace.myEnum

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

另请注意,这使用 Convert.ToInt32 而不是演员。这将处理枚举值,底层类型不是 Int32 。这仍然会引发一个 OverflowException ,但如果您的枚举的底层值超出了 Int32 的范围ie:如果是ulong,值为> int.MaxValue )。

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

这篇关于如何通过枚举名称和值的名称获取未知枚举的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆