获取枚举实例的名称 [英] Get name of Enum instance

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

问题描述

说我有这个枚举:

public enum MyEnum{
    ValueOne = 1,
    ValueTwo = 2,
    ValueThree = 3
}

然后此字段/变量:

public MyEnum myEnumInstance = MyEnum.ValueTwo;

我需要获得名称 myEnumInstance 通过来自另一类的反射

I need to get the name of myEnumInstance via reflection from another class.

我尝试过:

myClassInstance.GetType().GetField("myEnumInstance").GetValue(myClassInstance)

无论 myEnumInstance 为何总是返回 ValueOne 设置。

Which always returns ValueOne, no matter what myEnumInstance is set to.

如何通过反射获取枚举字段的字符串值/名称?

How can I get the string value/name of the enum field via reflection?

推荐答案

您不需要反射。您只需要调用 .ToString()

You don't need reflection. You just need to call .ToString().

myEnumInstance.ToString();

将会输出 ValueTwo ;

但是,如果您坚持使用反射,则以下示例可以正常工作:

However, if you insist on using reflection, the following example works just fine:

var myClassInstance = new MyClass();
myClassInstance.GetType()
               .GetField("myEnumInstance")
               .GetValue(myClassInstance);

public enum MyEnum
{
    ValueOne = 1,
    ValueTwo = 2,
    ValueThree = 3
}

public class MyClass
{
    public MyEnum myEnumInstance = MyEnum.ValueTwo;
}

请注意,在C#6中,您也可以使用一些强类型语法糖的nameof

Note that in C#6 you can also use nameof for some strongly-typed syntactic sugar:

myClassInstance.GetType()
               .GetField(nameof(myEnumInstance))
               .GetValue(myClassInstance);

如果您仍然无法访问该字段,那是因为它不是公开的,如您的示例代码,您需要在其中传递适当的绑定标志。

If you are STILL not able to access the field, it is because it is not public as described in your sample code, in which you'd need to pass in the appropriate binding flags.

myClassInstance
    .GetType()
    .GetField(nameof(myEnumInstance), 
        BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance)
    .GetValue(myClassInstance);

这篇关于获取枚举实例的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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