Generics with IL?

Can I use generators with an IL generator?

        DynamicMethod method = new DynamicMethod(
            "GetStuff", typeof(int), new Type[] { typeof(object) });

        ILGenerator il = method.GetILGenerator();

        ... etc
+5
source share
1 answer

Yes, it is possible, but not with the class DynamicMethod. If you are limited to using this class, you're out of luck. If you can use the object MethodBuilder, read on.

Emitting the body of a general method for most purposes and goals is no different from emitting the body of other methods, except that you can create local variables of general types. The following is an example of creating a generic method using MethodBuilderwith a generic argument T and creating a local type T:

MethodBuilder method;
//... Leaving out code to create MethodBuilder and store in method
var genericParameters = method.DefineGenericParameters(new[] { "T" });
var il = method.GetILGenerator();
LocalBuilder genericLocal = il.DeclareLocal(genericParameters[0]);

, . , method - MethodInfo MethodBuilder, , int :

il.EmitCall(OpCodes.Call, method.MakeGenericMethod(typeof(int)), new[] { typeof(int) }));
+8

All Articles