vendredi 17 juillet 2015

Assigning a lambda as a parameter to a generic method called through reflection

Consider a generic method as follow:

class SomeClass
{
    public static void SomeMethod<T>(Func<T>);
}

I would like to call this method using reflection. This is how far I could make it:

_SomeMethod = typeof(SomeClass).GetMethod("SomeMethod",
    BindingFlags.Public | BindingFlags.Static);
Type type = typeof(SomeType);
MethodInfo toBeCalled = _SomeMethod.MakeGenericMethod(type);
toBeCalled.Invoke(null, () => obj);

But it gives compile error:

Error CS1660: Cannot convert `lambda expression' to non-delegate type `object' (CS1660)

Which is absolutely acceptable but what's the work around?

Please keep in mind that the closure created using the lambda is something that I need, so don't eliminate it.





Aucun commentaire:

Enregistrer un commentaire