gpt4 book ai didi

c# - 如何使用反射创建基于 lambda 的委托(delegate)?

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:39 25 4
gpt4 key购买 nike

我有以下类(我无法更改它们,它们不在我的控制之下):

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>();
}

创建委托(delegate)和调用方法非常简单:

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是父类型并且我有一个匿名方法作为分配的方法?

最佳答案

您可以使用表达式树在运行时编译新函数:

Expression.Lambda(del, Expression.Constant(parent)).Compile()

关于c# - 如何使用反射创建基于 lambda 的委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com