Ultimately,
Reflection.Emit
is the best way to go. If you found that it is unsuitable, you probably missed something. I don't know what exactly you are trying to achieve, so just some hints:
You don't have to create a whole separate assembly with Emit. You may choose to create separate methods. You can use
System.Reflection.Emit.DynamicMethod
,
http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx[
^].
You can combine Emit with caching the results. Consider this highly simplified scenario:
Why would you need to pass some types through Reflection at all? Only because you need to create some processing of these types and their instances,
agnostic to those types, in advance. You take some types, process them with Reflection, and create some reflected artifacts in memory. If could be a set of
DynamicMethod
instances, or, better, delegate instances based on such methods, and some other information you dig out with Reflection: names, base types, etc.
Create a class to store all the results of such Reflection and Emit, call if, say,
ReflectionCache
.
All you need is to do it all once, not repeatedly. So, you need to create some dictionary indexed with some key. You can use
System.Type
as the key. Use, for example,
System.Collections.Generic.Dictionary<System.Type,ReflectionCache>
.
Each time you need to work with some type, you first looks for reflection cache in the dictionary. It if is found, use it: invoke delegate instanced obtained from
DynamicType
instances your emitted before, and so on. If the type is not found (remember, the type is the key), do extra Reflection and Emit. This way, you reach the goal: doing Reflection and Emit only once.
—SA