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?
obj? If you don't know theTinvolved, it's hard to see how you can create aFunc<T>from a lambda expression. Are you always just returning a constant value, or would you sometimes have other lambda expressions? More information would be really helpful.Funcwhich always just returnsobj? Nothing more complicated than that, ever? You say you want to keep the closure - does that mean you're going to change the value ofobjafterwards? Again, more clarity would be really helpful.SomeMethod()?SomeMethodbelongs to a library and I didn't write it!