gpt4 book ai didi

c# - 使用 DynamicMethod 进行运行时代码注入(inject)?

转载 作者:太空狗 更新时间:2023-10-29 23:34:44 27 4
gpt4 key购买 nike

考虑以下简单代码:

using System;   
class Test
{
delegate int FooDelegate(int i);
FooDelegate Foo = FooImplementation;
static int FooImplementation(int i)
{
return i + 1;
}

public static void Main()
{
Foo(1);
}
}

我想做的是将一些调试代码注入(inject)到 Foo 委托(delegate)中,这等效于:

FooDelegate Foo = delegate(int i)
{
try
{
DebugPrologue();
return FooImplementation(i);
}
finally
{
DebugEpilogue();
}
};

问题是我必须能够在运行时执行此操作,因此编译时和后处理方法是不可能的。

我最初的方法是使用 Delegate.Combine() 将序言和结尾方法添加到 Foo 委托(delegate)中。唉,这行不通,因为它会破坏返回值。

我目前的想法是使用 System.Reflection.Emit 和 DynamicMethod 作为潜在的解决方案。据我所知,我需要获取 FooImplementation 的 MethodInfo,获取其 MethodBody,将其转换为 DynamicMethod 并将我的 try-finally block 注入(inject)其中。

不幸的是,我完全不知道该怎么做。有人愿意伸出援手吗?或者您有其他(最好更简单的)想法吗?

编辑:此处的用例是调试 OpenGL 绑定(bind) (http://www.opentk.com)。我们必须注入(inject) 2226 个参数截然不同的方法,因此需要一种通用的方法。

最佳答案

您可以使用表达式。

var param = Expression.Parameter(typeof(int), "i");

Foo = Expression.Lambda(
Expression.TryFinally(
Expression.Block(
<expression for DebugPrologue>,
Expression.Invoke(<expression for FooImplementation>, param)),
<expression for DebugEpilogue>),
param)
.Compile();

这样,您就可以在运行时为序言和结语构建表达式。

关于c# - 使用 DynamicMethod 进行运行时代码注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4355869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com