generics with IL?

限于喜欢 提交于 2019-12-03 15:48:29

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

Emitting the body of a generic method is, for most intents and purposes, no different from emitting the body of other methods, except that you can make local variables of the generic types. Here is an example of creating a generic method using MethodBuilder with the generic argument T and creating a local of 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]);

To emit a call to that generic method from another method, use this code. Assuming method is a MethodInfo or MethodBuilder object that describes a generic method definition, you can emit a call to that method with the single generic parameter int as follows:

il.EmitCall(OpCodes.Call, method.MakeGenericMethod(typeof(int)), new[] { typeof(int) }));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!