我可以使用反射来检查方法中的代码吗? [英] Can I use reflection to inspect the code in a method?

查看:64
本文介绍了我可以使用反射来检查方法中的代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#反射API。我可以轻松地在程序集中加载类,方法等的 Type 信息,但是,现在,我想知道如何在方法内部加载和读取代码?

I'm playing around with the C# reflection API. I can easily load Type information of classes, methods etc. in an assembly, however, now I wonder how can I load and read the code inside a method?

推荐答案

基本答案:

您不能使用反射API(System.Reflection)。

You can't with the reflection API (System.Reflection).

原因是反射api设计用于元数据(类的类型,方法的名称和签名)。 ..),但不在数据级别(这将是IL流本身)。

The reason is that the reflection api is designed to work on Metadata (Type of Classes, Name and Signature of Methods, ...) but not on the data level (which would be the IL-stream itself).

扩展的答案:

您可以使用System.Reflection.Emit(例如ILGenerator类)发出(但不读取)IL。

You can emit (but not read) IL with System.Reflection.Emit (e.g. ILGenerator Class).

通过 MethodInfo.GetMethodBody(),您可以获取二进制IL流以实现方法。

Through MethodInfo.GetMethodBody() you can get the binary IL-stream for the implementation of a method. But thats usually completely useless by itself.

有外部库(例如 Cecil ),可用于读取/修改/添加/删除方法中的代码。

There are external libraries (like Cecil) that you can use to read/modify/add/delete code inside a method.

这篇关于我可以使用反射来检查方法中的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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