lundi 23 janvier 2017

How do you create a delegate based on a lambda using reflection?

I have the following classes (I can't change them, they are not in my control):

public abstract class BusinessBase { }
public class A : BusinessBase { }
public class B : BusinessBase { }

public class FooOne
{
    public void Foo<T>(FooDelegates.Func<T> func) where T : BusinessBase { ... }
}

public class FooTwo
{
    public void Foo<T>(FooDelegates.Func<T> func) where T : BusinessBase { ... }
}

public static class FooDelegates
{
    public delegate TResult Func<TResult>();
}

Creating a delegate and calling the method is pretty straightforward:

var f1 = new FooOne();
f1.Foo(() => new A());

However, trying to use reflection to do this is proving to be a bit complicated. I have the following function which I cannot seem to finish:

public class GenericHelper
{
    // Parent can be A or B or etc...
    // Child is FooOne or FooTwo or etc...
    public void Relate(object parent, object child)
    {
        var mi = child.GetType().GetMethod("Foo");
        var gmi = mi.MakeGenericMethod(parent.GetType());

        // This next part obviously won't compile...
        var del = typeof(FooDelegates.Func<>).MakeGenericType(parent.GetType());
        FooDelegates.Func<parent.GetType()> del = () => parent;
        gmi.Invoke(child, new object[] { del });
    }
}

How do I correctly generate a FooDelegates.Func<T> where T is the parent type and I have an anonymous method as the assigned method?





Aucun commentaire:

Enregistrer un commentaire