问题描述
当我在运行时拥有枚举的System.Type并检查BaseType为System.Enum时,我的工作方式是如何精确创建枚举的实例,我的值是与项目匹配的int值在神秘的枚举中。
I have a problem working out how exactly to create an instance of an enum when at runtime i have the System.Type of the enum and have checked that the BaseType is System.Enum, my value is an int value matching an item in the mystery Enum.
到目前为止,我所拥有的代码只是上述逻辑。
The code i have so far is just the logic described above as shown below.
if (Type.GetType(type) != null)
{
if (Type.GetType(type).BaseType.ToString() == "System.Enum")
{
return ???;
}
}
在过去与Enums合作时,我总是知道在代码时,我试图解析该枚举,但是在这种情况下,我很困惑,而且运气不好,以谷歌友好的方式表达了我的问题...我通常会做类似的事情
When working with Enums in the past i have always know at code time which enum i am trying to parse but in this scenario im confused and have had little luck articulating my question in a google friendly way... I would usually do something like
(SomeEnumType)int
但由于我不知道代码时的EnumType如何实现相同的目的?
but since i dont know the EnumType at code time how can i achieve the same thing?
推荐答案
使用方法c> Enum 类:
var enumValue = Enum.ToObject(type, value);
或者像您提供的代码一样:
Or like the code you provided:
if (Type.GetType(type) != null)
{
var enumType = Type.GetType(type);
if (enumType.IsEnum)
{
return Enum.ToObject(enumType, value);
}
}
这篇关于使用C#中的反射创建具有字符串值的未知枚举实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!