.NET:使用 Reflection.Emit 动态克隆现有方法

发布于 2024-09-17 18:44:49 字数 176 浏览 4 评论 0原文

有很多关于如何使用 Reflection.Emit 创建方法的线程,但我找不到任何关于克隆或复制现有方法的线程。

我想复制一个现有的类并向其中添加一些附加字段。我在复制方法时遇到问题。我读到您不能简单地从主体中获取 IL 代码,因为令牌属于现有模块。是否可以使用 MethodBuilder 将类方法克隆或复制到另一个类?

There are plenty of threads on how to create a Method using Reflection.Emit but I cannot find any on Cloning or copying an Existing Method.

I would like to copy an existing class and add a few more additional fields to it. I am having trouble copying the methods. I have read that you cannot simply take the IL Code from the body because tokens pertain to the existing module. Is it possible to clone or copy a class method another class using the MethodBuilder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀中猫帐中妖 2024-09-24 18:44:49

嗯,这是可能的,但相当尴尬。问题是 MethodBody 类只允许您以字节数组的形式检索 IL。然而,ILGenerator.Emit() 方法没有重载,只能将这些字节复制到动态方法中。它要求您使用正确的重载来生成正确的 IL 指令。

这不仅对于确保始终生成正确的 IL 很重要,而且还用于收集有关动态方法的信息。特别是该方法所需的堆栈大小。能够使用 ILGenerator.Emit() 的唯一方法是编写代码,首先将字节反编译为其相应的 IL 指令。这并非不可能,只是需要做很多工作。我想不出什么捷径。

Well, it is possible but quite awkward. The problem is that the MethodBody class only lets you retrieve the IL as an array of bytes. The ILGenerator.Emit() method however does not have an overload to just copy those bytes into the dynamic method. It requires you to use the proper overload to generate the proper IL instruction.

That's important not just to ensure that you always generate correct IL, it is also used to collect info about the dynamic method. Specifically the stack size that's required for the method. The only way to be able to use ILGenerator.Emit() is to write code that decompiles the bytes first into their corresponding IL instructions. That's not impossible, just a lot of work. I can't think of a short-cut.

苦行僧 2024-09-24 18:44:49

查看 PostSharp 及其底层技术。

Have a look on PostSharp and its underlying technology.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文