mat*_*lin 39 c# reflection enums
我有一个简单的枚举
public enum TestEnum
{
TestOne = 3,
TestTwo = 4
}
var testing = TestEnum.TestOne;
Run Code Online (Sandbox Code Playgroud)
我想通过反射检索它的值(3).关于如何做到这一点的任何想法?
Mil*_*dis 49
好问题垫.
问题的情景如下:
您有一些未知的枚举类型和该类型的某些未知值,并且您希望获得该未知值的基础数值.
这是使用反射执行此操作的单行方式:
object underlyingValue = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));
Run Code Online (Sandbox Code Playgroud)
如果值恰好是TestEnum.TestTwo
,那么value.GetType()
将等于typeof(TestEnum)
,Enum.GetUnderlyingType(value.GetType())
将等于typeof(int)
并且值将为3(盒装; 有关拳击和更多有关拳击的详细信息,请参阅http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx拆箱值).
为什么需要编写这样的代码?在我的例子中,我有一个例程,它将值从视图模型复制到模型.我在ASP.NET MVC项目中的所有处理程序中使用它作为一个非常干净和优雅的体系结构的一部分,用于编写处理程序,这些处理程序没有Microsoft模板生成的处理程序所带来的安全问题.
该模型由实体框架从数据库生成,它包含int类型的字段.viewmodel有一个枚举类型的字段,让我们称之为RecordStatus,我在项目的其他地方定义了它.我决定在我的框架中完全支持枚举.但是现在模型中字段的类型与视图模型中相应字段的类型不匹配.我的代码检测到这一点并使用类似于上面给出的单行代码将枚举转换为int.
OLP*_*OLP 31
您可以使用System.Enum帮助程序:
System.Type enumType = typeof(TestEnum);
System.Type enumUnderlyingType = System.Enum.GetUnderlyingType(enumType);
System.Array enumValues = System.Enum.GetValues(enumType);
for (int i=0; i < enumValues.Length; i++)
{
// Retrieve the value of the ith enum item.
object value = enumValues.GetValue(i);
// Convert the value to its underlying type (int, byte, long, ...)
object underlyingValue = System.Convert.ChangeType(value, enumUnderlyingType);
System.Console.WriteLine(underlyingValue);
}
Run Code Online (Sandbox Code Playgroud)
输出
3
4
Pra*_*ana 21
完整代码:如何在C#中使用反射获取枚举值
MemberInfo[] memberInfos = typeof(MyEnum).GetMembers(BindingFlags.Public | BindingFlags.Static);
string alerta = "";
for (int i = 0; i < memberInfos.Length; i++) {
alerta += memberInfos[i].Name + " - ";
alerta += memberInfos[i].GetType().Name + "\n";
}
Run Code Online (Sandbox Code Playgroud)
你为什么需要反思?
int value = (int)TestEnum.TestOne;
Run Code Online (Sandbox Code Playgroud)
如果您已在仅反射上下文中加载程序集,则 GetValue 和 GetValues 方法将不起作用。但我们可以使用另一种方法:
var val = typeof(MyEnum).GetFields()
.Where(fi => fi.IsLiteral && fi.Name == "TestOne")
.Select(fi => fi.GetRawConstantValue())
.First();
Run Code Online (Sandbox Code Playgroud)