IL的仿制药? [英] generics with IL?

查看:126
本文介绍了IL的仿制药?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在IL Generator中使用泛型?

Is it possible to use generics with the IL Generator?

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

        ILGenerator il = method.GetILGenerator();

        ... etc

推荐答案

是的,可以,但DynamicMethod类不可以.如果您被限制使用此类,那么您就不走运了.如果可以改用MethodBuilder对象,请继续阅读.

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.

在大多数情况下,泛型方法的主体与其他方法的主体没有什么不同,不同之处在于,您可以使泛型类型成为局部变量.这是一个使用MethodBuilder和泛型参数T创建泛型方法并创建类型T的局部变量的示例:

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]);

要从另一个方法发出对该泛型方法的调用,请使用此代码.假设method是描述通用方法定义的MethodInfoMethodBuilder对象,则可以使用单个通用参数int发出对该方法的调用,如下所示:

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) }));

这篇关于IL的仿制药?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆