Delegate.CreateDelegate VS DynamicMethod的VS防爆pressionCreateDelegate、Delegate、VS、pression

2023-09-02 21:56:13 作者:青年领袖。

关于Making反射飞翔和探索代表 ...

如果我需要建立代表 Func键< T,TResult> 来对动态加载的类型我可能会使用的方法(1) Delegate.CreateDelegate (2) DynamicMethod的(3)防爆pression 树木。

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.

其中动态绑定的方法将你preFER为什么?

Which dynamic binding method would you prefer and why?

推荐答案

如果他们是实际存在的,你有一个的MethodInfo 的方法,他们有正确的签名,那么我会说 Delegate.CreateDelegate 是正确的方式去 - 这不正是你想要什么,有没有什么大惊小怪的。我会使用 DynamicMethod的或EX pression树,如果我需要建立一个委托执行这是不是已经捕获方法的一些逻辑。

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.

防爆pression树(IMO,而我没有使用 DynamicMethod的愤怒)稍微容易比 DynamicMethod的,但他们更多的限制 - 基本上他们只能重新present单前pression(它可以调用过程中的另一种方法,)。 DynamicMethod的为您提供了很大的灵活性,但你需要了解IL还算不错。

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.

帮助吗?