我有以下类(我无法改变他们,他们是不是在我的控制):如何使用反射创建基于lambda的委托?
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
是父类,我有一个匿名方法的分配方法?
您需要创建和编译'()'表达式树 – SLaks