I need to implement the method:
object GetFactory(Type type);
This method needs to return a Func
You use Delegate.CreateDelegate, i.e. from a MethodInfo; below, I've hard-coded, but you would use some logic, or Expression, to get the actual creation method:
using System;
using System.Reflection;
class Foo {}
static class Program
{
static Func GetFactory()
{
return (Func)GetFactory(typeof(T));
}
static object GetFactory(Type type)
{
Type funcType = typeof(Func<>).MakeGenericType(type);
MethodInfo method = typeof(Program).GetMethod("CreateFoo",
BindingFlags.NonPublic | BindingFlags.Static);
return Delegate.CreateDelegate(funcType, method);
}
static Foo CreateFoo() { return new Foo(); }
static void Main()
{
Func factory = GetFactory();
Foo foo = factory();
}
}
For non-static methods, there is an overload of Delegate.CreateDelegate that accepts the target instance.