我有以下课程(我无法改变它们,它们不在我的掌控之中):
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>();
}
创建委托并调用该方法非常简单:
var f1 = new FooOne();
f1.Foo(() => new A());
然而,尝试使用反射来做到这一点被证明有点复杂。我有以下功能,我似乎无法完成:
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 });
}
}
如何正确生成FooDelegates.Func<T>
,其中T
是父类型,我有一个匿名方法作为指定方法?
答案 0 :(得分:1)
您可以使用表达式树在运行时编译新函数:
Expression.Lambda(del, Expression.Constant(parent)).Compile()