samedi 31 octobre 2015

Issues in calling generic method through reflection with a delegate parameter

I've been messing around with this for over an hour and just cannot seem to get it right. Here's one of the exceptions I am getting:

Error: Object of type 'System.Func1[System.Object]' cannot be converted to type 'System.Func1[System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable1[System.Object]]]'.

Basically I have a generic factory method which looks like this

ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack,
    Processor manager) where TResult : class;

and I am trying reflect into, but the Func> is causing me problems. Here's the code I have in trying to call it:

var infer = Factory.CreateReturnInference(); //Keypair value (type, type) is NOT an NormalOutputFactory in this instance
Func<object> callBack = () => subTypes;

var toRun = Factory.GetType()
            .GetMethod("CreateOutput", BindingFlags.Public | BindingFlags.Instance)
            .MakeGenericMethod(infer.Key, infer.Value)
            .Invoke(Factory,
                new object[] {callBack, Manager}) as
            ReturnItem<object>;

The keypair value returned from Factory.CreateReturnInference is used to specifiy the generic parmeters, and just to provide clarity on it's implementation: (Warning very ugly code, violates open-close amount other stuff :)):

public KeyValuePair<Type, Type> CreateReturnInference()
    {
        return this is NormalOutputFactory
            ? new KeyValuePair<Type, Type>(typeof (object), typeof (Log))
            : new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (Enum));
    } 

The general question is: When calling a generic method through reflection how do I specify a Func parameter?





Aucun commentaire:

Enregistrer un commentaire