是否有可能在.NET中修改方法体在运行时?有可能、方法、NET

2023-09-03 01:55:33 作者:泪已成海却未蓝

我知道这是可能的(理论上),以创建一个新的类型在运行时,但有可能修改现有的类型在运行时的方法体?我的计划(如果我能得到这个工作)是标记了一个自定义属性的方法,然后在运行时查找与属性的方法,并插入一些我自己的code到方法体。

I know that it is possible (in theory) to create a new type at run-time, but is it possible to modify a method body of an existing type at run-time? My plan (if I can get this to work) is to tag up methods with a custom attribute, and then at run-time search for methods with the attribute, and insert some of my own code into the method body.

有什么建议?

我想,如果我不能得到这种方法工作,我总是可以在基类虚方法(使用属性),结合静态工厂吐出派生动态类型与我的运行 - 时生成的子类中的方法。这不会是相当的清洁,但使用。

I suppose if I can't get that approach to work, I could always go with a virtual method in a base class (with the attributes), combined with a static factory to spit out a derived dynamic type with my run-time generated method in the child class. This would not be quite as clean to use though.

推荐答案

PostSharp 这是一个aftercompiler,确实类似于你的东西形容,使用属性在code标志注射点,唯一的区别是,它是在编译的时候。

PostSharp which is an aftercompiler, does something similar to what you describe, using attributes to mark injection points in the code, only difference is that it does it at compile time.

但你也可以做到这一点在运行时不会被改变的方法体,但通过使用从派生类ContextBoundObject 这是一个.NET类,可以让你拦截所有发针对它的调用。这里是一个 MSDN杂志文章描述了如何使用ContextBoundObject AOP做。 (检查的方面的.Net 的文章的部分)

But you can also do it at runtime not by changing method bodies but by using classes derived from ContextBoundObject which is a .Net class that lets you intercept all the calls made against it. Here is a MSDN Magazine article describing how to do AOP using ContextBoundObject. (Check the aspects in .Net part of the article)

和作为第三个选择,你可以使用动态code代(Reflection.Emit的或codeDOM)与属性和虚拟方法,动态生成派生类的组合,您可以将您的code,但这是最痛苦的方式来做到这一点。

And as a third option you can use dynamic code generation (Reflection.Emit or CodeDom) in combination with attributes and virtual methods to dynamically generate derived classes where you can insert your code, but this is the most painful way to do it.

编辑:

有一个第四个选项使用净非托管的分析API 拦截方法JIT -ing和替换提前JIT-ING法机构。 该技术成功地以嘲笑,静态方法,非虚方法,甚至密封类使用JustMock(的Telerik)。

There's a forth option to use .Net unmanaged profiling API to intercept method JIT-ing and replace method bodies ahead of JIT-ing. This technique is sucessfully used by JustMock (Telerik) in order to mock, static methods, non virtual methods and even sealed classes.