سؤال

I work in a code base that is quite large and today I found a project that was emitting IL code inside a normal class.

The project containing the IL code being emitted was a implementation of a Service Locator MSDN Desctiption.

What are the advantages of doing this and why would this be done as apposed to using the C# language?

هل كانت مفيدة؟

المحلول

Typically this is done to circumvent the overhead of using reflection, using information only available at runtime.

You would then use reflection, which can be slow depending on what you do, to build a new piece of code that works directly with the data given to it, without using reflection.

Advantages:

  • Performance

Disadvantages:

  • Hard to debug
  • Hard to get right
  • Hard to read code afterwards
  • Steep learning curve

So you need to ensure it's really worth the price before embarking on this.

Note that this is a general answer. In the specific case you came across, there is no way to answer why this was done nor which particular advantages (or disadvantages) you would have without actually seeing the code.

نصائح أخرى

There are many uses for this.
One of the more often used scenario is for changing/injecting code on the fly:
.NET CLR Injection: Modify IL Code during Run-time


A good tutorial that help me to understand a good use for it is: Dynamic... But Fast: The Tale of Three Monkeys, A Wolf and the DynamicMethod and ILGenerator Classes


Good luck

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top