开发者

.NET: Clone an Existing Method Dynamically with Reflection.Emit

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 exist开发者_JAVA技巧ing module. Is it possible to clone or copy a class method another class using the MethodBuilder?


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.


Have a look on PostSharp and its underlying technology.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜