如何更换方法实现在运行时?方法

2023-09-02 10:53:27 作者:你拉着提琴优雅美丽~

我想有属性的getter和方法,我可以用我自己的自定义属性装饰,并基于该属性的presence用不同的实现替换方法体。此外,不同的实施将需要知道给它装饰的方法,自定义属性构造函数的参数。

I'd like to have property getters and methods that I can decorate with my own custom attribute and based on the presence of that attribute replace the method bodies with a different implementation. Also, that different implementation will need to know the constructor arguments given to the custom attribute where it decorates the method.

这显然可以用AOP做,像PostSharp或李林甫,但我不知道是否有一种方法可以做到这一点,不涉及一个生成后处理步骤,因为补充说,复杂的项目比我更preFER。

This can obviously be done with AOP, like PostSharp or LinFu, but I'm wondering if there's a way to do this that does not involve a post-build processing step because adding that complicates the project more than I would prefer.

推荐答案

采用传统的.Net API的有没有办法做到这一点。方法体被固定在编译时,不能改变。

Using the traditional .Net APIs there is no way to achieve this. Method bodies are fixed at compile time and cannot be changed.

我说的传统,但因为在profiler ENC的API在技术上可以更改方法体。但这些API操作在约束的情况下,并且不被认为是通用的API。

I say traditional though because with the profiler and ENC APIs it's technically possible to change method bodies. But these APIs operate in constrained circumstances and are not considered to be general purpose APIs.