mercredi 19 juillet 2017

How to create an instance of type Func

I have a little problem with Reflection's Invoke() of a Generic Method that takes in a Func<TModel, TResult> as parameter.

For example

public class A
{
    public List<TResult> SomeGenericMethod<TResult> (Func<TModel, TResult> query)
    {
        // some code to process the query here
    }
}

public class TModel1
{
    // stuff
}

public class TResult1
{
    // stuff
    public static Func<TModel1, TResult1> SomeMethod()
    {
        // return a lamda query
    }
}

// where things get hairy, due to nature of the code, TModel and TResult are
// identified at run time and has to be initiated from Reflection
public SomeResult SomeProcessingFunction(SomeArgument arg)
{
    // stuff
    Type tResultType; // some Reflection to get TResult1 type
    Type tModelType; // some Reflection to get TModel1 type
    var a; // some Reflection to get an A object        
    MethodInfo method; // some Reflection to get SomeGenericMethod
    object result = method.MakeGenericMethod(tResultType).Invoke(a, new object[]
        {
            // need to somehow pass TResult1.SomeMethod() as object
        });
}

So my question is how do I pass TResult1.SomeMethod() as a System.Func2<...> to the Invoke() method so I can run A.SomeGenericMethod<TResult>(...)

Thank you!





Aucun commentaire:

Enregistrer un commentaire