Delegate.CreateDelegate vs DynamicMethod vs Expression [英] Delegate.CreateDelegate vs DynamicMethod vs Expression

查看:96
本文介绍了Delegate.CreateDelegate vs DynamicMethod vs Expression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的问题反思飞行并探索代表 ...



如果我需要创建代表 Func< T,TResult> 到动态加载类型的方法我可以使用(1) Delegate.CreateDelegate (2) DynamicMethod 3)表达式树。



让我们说,动态加载的类型/方法的集合在应用程序启动时被反映一次配置并在应用程序的整个生命周期中使用(启动性能不是问题,也不是内存),代理将以强类型的方式进行缓存和分派。这些代理是同时访问的热门路径。



你喜欢哪种动态绑定方法,为什么?

解决方案

如果他们实际上是现有的方法,你有一个 MethodInfo ,而且他们有正确的签名,那么我会说 Delegate.CreateDelegate 是正确的方法 - 它完全符合你想要的,没有大惊小怪。我需要使用 DynamicMethod 或表达式树,如果我需要构建一个委托来执行一些尚未在方法中捕获的逻辑。



表达式树是(IMO,而且我没有使用 DynamicMethod 在愤怒中)比 DynamicMethod ,但是它们更受限制 - 基本上它们只能表示一个表达式(当然也可以称之为另一种方法)。 DynamicMethod 给你很大的灵活性,但是你需要很好地理解IL。



有帮助吗? p>

Questions about Making reflection fly and exploring delegates...

If I need to create delegates Func<T, TResult> to methods on dynamically loaded types I could potentially use (1) Delegate.CreateDelegate (2) DynamicMethod (3) Expression trees.

Lets say the set of dynamically loaded types/methods are reflected once at application startup via config and used throughout the lifetime of the app (start-up performance is not an issue and neither is memory), the delegates are cached and dispatched to in a strongly-typed way. These delegates are hot paths accessed concurrently.

Which dynamic binding method would you prefer and why?

解决方案

If they're actually existing methods which you have a MethodInfo for, and they have the right signatures, then I'd say Delegate.CreateDelegate is the right way to go - it does exactly what you want, with no fuss. I'd use DynamicMethod or expression trees if I needed to build a delegate to execute some logic which wasn't already captured in a method.

Expression trees are (IMO, and I haven't used DynamicMethod in anger) slightly easier to use than DynamicMethod, but they're more restricted - basically they can only represent a single expression (which could call another method, of course). DynamicMethod gives you lots of flexibility, but you need to understand IL reasonably well.

Does that help?

这篇关于Delegate.CreateDelegate vs DynamicMethod vs Expression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆