动态替换一个C#方法的内容? [英] Dynamically replace the contents of a C# method?
问题描述
我想要做的是怎么改,当它被称为C#方法执行,这样我可以这样写:
What I want to do is change how a C# method executes when it is called, so that I can write something like this:
[Distributed]
public DTask<bool> Solve(int n, DEvent<bool> callback)
{
for (int m = 2; m < n - 1; m += 1)
if (m % n == 0)
return false;
return true;
}
在运行时,我需要能够分析具有分布式属性(我已经可以做),然后插入code之前,函数体执行,并在函数返回之后方法。更重要的是,我需要能够做到这一点,而无需修改code,其中解决被调用或在函数的开始(在编译时;在运行时,这样做是客观的)
At run-time, I need to be able to analyse methods that have the Distributed attribute (which I already can do) and then insert code before the body of the function executes and after the function returns. More importantly, I need to be able to do it without modifying code where Solve is called or at the start of the function (at compile time; doing so at run-time is the objective).
目前,我已经尝试code的该位的(假设t是能够解决存储在类型,m是解决的一个MethodInfo)的:
At the moment I have attempted this bit of code (assume t is the type that Solve is stored in, and m is a MethodInfo of Solve):
private void WrapMethod(Type t, MethodInfo m)
{
// Generate ILasm for delegate.
byte[] il = typeof(Dpm).GetMethod("ReplacedSolve").GetMethodBody().GetILAsByteArray();
// Pin the bytes in the garbage collection.
GCHandle h = GCHandle.Alloc((object)il, GCHandleType.Pinned);
IntPtr addr = h.AddrOfPinnedObject();
int size = il.Length;
// Swap the method.
MethodRental.SwapMethodBody(t, m.MetadataToken, addr, size, MethodRental.JitImmediate);
}
public DTask<bool> ReplacedSolve(int n, DEvent<bool> callback)
{
Console.WriteLine("This was executed instead!");
return true;
}
不过,MethodRental.SwapMethodBody仅适用于动态模块;而不是那些已经被编译并存储在装配。
However, MethodRental.SwapMethodBody only works on dynamic modules; not those that have already been compiled and stored in the assembly.
所以我在寻找一种方式,切实做好SwapMethodBody对已存储在加载和执行程序集方式
So I'm looking for a way to effectively do SwapMethodBody on a method that is already stored in a loaded and executing assembly.
请注意,这不是一个问题,如果我的方法完全复制到一个动态模块,但在这种情况下,我需要找到一种方法跨越IL复制以及更新所有的呼叫解决()这样,他们将指向新副本。
Note, it is not an issue if I have to completely copy the method into a dynamic module, but in this case I need to find a way to copy across the IL as well as update all of the calls to Solve() such that they would point to the new copy.
推荐答案
试想影响的,如果这是可能的。例如,您可以替换字符串
类的内容和发泄havock。一旦一个方法是由CLR装载它不能被修改。你可以看看AOP和库如城堡DynamicProxy 由嘲笑框架中使用如犀牛制品。
Just think of the implications if this was possible. You could for example replace the contents of the String
class and wreak havock. Once a method is loaded by the CLR it cannot be modified. You may take a look at AOP and libraries such as Castle DynamicProxy that are used by mocking frameworks such as Rhino Mocks.
这篇关于动态替换一个C#方法的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!