One approach is using such an interesting thing as
System.Reflection.Emit.DynamicMethod
; please see:
http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx[
^].
The idea is: you don't have to create methods which are counted as being declared in certain type. In fact, on low level, even the instance (non-static) method declared in some class or a structure has only two aspects binding it to a certain type: 1) it has full access to all its members, 2) it has the first implicit parameter used to pass "this", the reference to the class instance. You can implement both features with dynamic methods, and also such an exotic thing as (1) without (2) — this is done via the flag
skipVisibility
passed in some constructors (
http://msdn.microsoft.com/en-us/library/xc6e708b.aspx[
^]), and passing "this" is implemented as adding the first parameter explicitly and using the parameter
Owner
.
This is described here:
http://msdn.microsoft.com/en-us/library/exczf7b9.aspx[
^].
Pay attention for the section "To define and execute a dynamic method that is bound to an object".
The dynamic method can be called directly using its
Invoke
methods or by creation a delegate using
CreateDelegate
methods. The fastest way of calling the dynamic method repetitively is calling this delegate. One problem is that if you want to call the delegate with different targets, you should re-bind it by calling
CreateDelegate
again and again. This is very expensive, as well as repetitive call to the
Invoke
. One resolution of this problem is using dynamic method without binding to the object, but passing a reference explicitly, which also supports polymorphism. For access, you need to use
skipVisibility
with the constructor referenced above.
Now, the amazing thing is that Reflection does not count dynamic methods, at least not as methods belonging to any types! They exist only during run time, so it might not be exactly a solution you are looking for. However, for any practical purposes, they work exactly as any "regular" methods called through delegate instances, with decent performance of direct method calls. Besides, in certain situations you can create highly effective manually emitted code with extraordinary flexibility typical for Reflection but without its performance cost! I would highly recommend to try it out. If you already learned how to emit the code (which is the hardest part), using dynamic methods may seem relatively easy for you.
—SA