Delegate.CreateDelegate vs DynamicMethod vs Expression

前端 未结 2 1307
遇见更好的自我
遇见更好的自我 2020-12-13 04:25

Questions about Making reflection fly and exploring delegates...

If I need to create delegates Func to methods on dynamically loaded t

相关标签:
2条回答
  • 2020-12-13 05:11

    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?

    0 讨论(0)
  • 2020-12-13 05:23

    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

    Update

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

    0 讨论(0)
提交回复
热议问题