C# Delegate.CreateDelegate vs DynamicMethod vs Expression

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/597819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:44:49  来源:igfitidea点击:

Delegate.CreateDelegate vs DynamicMethod vs Expression

c#.netreflectiondynamicdelegates

提问by jsw

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) Expressiontrees.

如果我需要为Func<T, TResult>动态加载的类型的方法创建委托,我可能会使用 (1) Delegate.CreateDelegate(2) DynamicMethod(3)Expression树。

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?

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

采纳答案by Jon Skeet

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

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

Expression trees are (IMO, and I haven't used DynamicMethodin 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). DynamicMethodgives you lots of flexibility, but you need to understand IL reasonably well.

表达式树(IMO,我没有DynamicMethod在愤怒中使用过)比 更容易使用DynamicMethod,但它们更受限制 - 基本上它们只能表示单个表达式(当然可以调用另一种方法)。DynamicMethod为您提供了很大的灵活性,但您需要相当好地理解 IL。

Does that help?

这有帮助吗?

回答by flq

Via Ayende's blog I got this interesting link which shows off the kind of things you can do with Dynamic Methods. As an example it is quite understandable:
Accelerating Enum-Based Dictionaries with Generic EnumComparer

通过 Ayende 的博客,我得到了这个有趣的链接,它展示了使用动态方法可以做的事情。举个例子,这是很容易理解的:
使用通用 EnumComparer 加速基于枚举的字典

Update

更新

One should note that in the world of WinRT, Reflection.Emitis unavailable - some information can be found here

应该注意的是,在 WinRT 的世界中,Reflection.Emit是不可用的 - 可以在此处找到一些信息