如何通过枚举和值名称的名称来获得未知的枚举值? [英] how to get value of an unknown enum by name of enum and name of value?
问题描述
有关问这个问题抱歉,但我没有找到此任务的正确解决方案:
我有一个枚举,它被命名为myEnum( myEnum不被功能)
知我需要得到myEnum值
实例的int值:结果
一程序员命名为它的枚举myEnum:
公共枚举myEnum
{
富= 1,
栏= 2,
}
我的功能应做到以下几点:$ b $
<$ p $:乙获得的myEnum富由字符串值
功能应该打开p> 公众诠释GetValueOf(字符串EnumName,串EnumConst)
{
}
所以,当程序员通过它打开:
int类型的= GetValueOf(myEnum ,富);
这应该返回1
和时程序员b有一个枚举名为MySpace的,希望与值5回栏
int类型的= GetValueOf(MySpace的,酒吧)
应该返回5
我怎样才能做到这一点?
您可以使用的 Enum.Parse 要做到这一点,但你需要的枚举类型的完全限定类型名称,例如:SomeNamespace。 myEnum
:
公共静态INT GetValueOf(字符串enumName,串enumConst)
{
型enumType = Type.GetType(enumName);
如果(enumType == NULL)
{
抛出新的ArgumentException(指定枚举类型找不到,enumName);
}
对象值= Enum.Parse(enumType,enumConst);
返回Convert.ToInt32(值);
}
另外请注意,这里使用 Convert.ToInt32
,而不是演员。这将处理枚举值与基础类型不属于的Int32
。这仍然会抛出发生OverflowException
,但是,如果你的枚举有一个的Int32
的范围之外的潜在价值(即:如果它是一个ULONG作为值是> int.MaxValue
)
。
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?
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
).
这篇关于如何通过枚举和值名称的名称来获得未知的枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!