Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...