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); //Actually SomeType is extracted using reflection and it's not fixed
MethodInfo toBeCalled = _SomeMethod.MakeGenericMethod(type);
object obj = Activator.CreateInstance(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.
[UPDATE]
To clarify the situation so it makes sense; the functor created using the lambda is an instantiator used by SomeMethod
to create an instance of the class SomeType
. But I don't want to actually create the object in functor, instead return it from a collection of instantiated objects from before. The easiest way would be having the obj
in a closure returned by the lambda, don't you think?
It doesn't sound like you really need a lambda expression here. You can build a function to return a constant value very easily using expression trees:
var expression = Expression.Constant(obj, type);
var delegateType = typeof(Func<>).MakeGenericType(type);
var func = Expression.Lambda(delegateType, expression).Compile();
toBeCalled.Invoke(null, func);
See more on this question at Stackoverflow