mercredi 29 juin 2016

casting error while dynamically invoking a function that returns a custom type

I have a custom type, customType, defined under tool1.class1.

I am using some other method, under tool1.class2, with a name routine1, that returns a "List of customType", as follows.

This code returns a list of customtype with no errors:

    List<tool1.class1.customType> result1 = new List<tool1.class1.customType>();
    result1 = tool1.class2.routine1(argsAsStr, p_values);

The following code also works fine and returns an object, as follows:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class2");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    object result2 = method.Invoke(instance, parametersArray); 

However, when I try to use the type List, instead of the object, then I receive the following error:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class2");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    List<tool1.class1.customType> result2 = method.Invoke(instance, parametersArray)

Error message:

Error: Cannot implicitly convert type 'object' to 'System.Collections.Generic.List<tool1.class1.customType>'. 
An explicit conversion exists (are you missing a cast?) 

How can I overcome this casting error, and, hopefully, return "not" an object but "a list of customType" after invoke method??

Thanks in advance for your interest and contributions,

Aykut





Aucun commentaire:

Enregistrer un commentaire