lundi 17 février 2020

Unable to retrieve enum type if the definition is located inside a class via reflection

How to retrieve the enum type if the enum is defined within a class?

Adapted from the code here:

namespace GetEnumReflectionTesting
{
    enum Foo { Bar = 5 }
    public class MyClass
    {
        enum Foo { Bar =6}
    }


    class Program
    {
        static void Main()
        {
            // Get the assembly containing the enum - Here it's the one executing
            var assembly = Assembly.GetExecutingAssembly();


            var enumType = assembly.GetType("GetEnumReflectionTesting.Foo"); //this obtains the GetEnumReflectionTesting.Foo
            var enumBarValue = enumType.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);

            var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass.Foo"); //but instead of GetEnumReflectionTesting.MyClass.Foo, this returns a null!
            var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);
        }
    }
}

Here's something interesting, enumType retrieves the GetEnumReflectionTesting.Foo as expected, but enumType2 instead of retrieve GetEnumReflectionTesting.MyClass.Foo, it returns a null!

So what is the robust way to retrieve the enum type regardless of whether it is defined within a class, or not?

Note that in my scenario, the Foo enum is defined within a class, and I get it from third party vendor which I can't change. So don't suggest me moving the Foo enum outside of the class.





Aucun commentaire:

Enregistrer un commentaire