mardi 22 janvier 2019

Get name and values of enumerator from ReflectionOnlyGetType - operation invalid in ReflectionOnlyContext

I need to be able to enumerate through values of an enumerator in a separate assembly for which I only have the assembly qualified name.

I am able to determine the assembly qualified name, but I can't resolve the 'The requested operation is invalid in the ReflectionOnly context.' when I try to enumerate it.

My main code, in assembly DevExample:

using System;
using ClassLibrary;

namespace DevExample
{
    public class Program
    {
        static void Main(string[] args)
        {           
            Type myEnumType = MyEnum.One.GetType();

            WriteToConsole(myEnumType);

            Type myEnumType_null = Type.GetType(myEnumType.FullName); // will return null

            string assemblyName = myEnumType.AssemblyQualifiedName;
            // assemblyName will be "ClassLibrary.MyEnum, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";

            Type myEnumTypeFromReflection = Type.ReflectionOnlyGetType(assemblyName, true, false); // Will get type succesfully

            WriteToConsole(myEnumTypeFromReflection);
        }

        private static void WriteToConsole(Type enumType)
        {
            foreach (int val in Enum.GetValues(enumType))
            {
                Console.WriteLine("{0} - {0}", Enum.GetName(enumType, val));
            }
        }
    }
}


Then in another assembly (ClassLibrary.dll) I just defined a simple enumerator

namespace ClassLibrary
{
    public enum MyEnum
    {
        Zero = 0,
        One = 1,
        Two = 2
    };
}

On the second write to console, I get:

The requested operation is invalid in the ReflectionOnly context.

I need to do this to validate an .xml that defines which enumerators a particular piece of hardware is using.

Previous code has just loaded a dictionary with the name and types manually, but given that the .xml file is able to contain the assembly qualified name, it should be able to do this dynamically.





Aucun commentaire:

Enregistrer un commentaire