Get name of Enum instance [closed]

旧巷老猫 提交于 2020-07-21 06:07:53

问题


Say I have this enum:

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

And then this field/variable:

public MyEnum myEnumInstance = MyEnum.ValueTwo;

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

I tried:

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

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?


回答1:


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

myEnumInstance.ToString();

which will output "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;
}

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


来源:https://stackoverflow.com/questions/36731711/get-name-of-enum-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!