我现在使用 System.Reflection.Emit 有一段时间了,发现它(谁没有?)和容易出错一样痛苦。
你知道 IL 生成器周围是否有一个很好的包装器,我可以依靠它以比直接使用 SRE 更安全、更容易的方式发出 IL?
编辑:
我知道操作表达式树肯定比直接发出 IL 更容易、更安全,但它们现在也有一些限制。我不能创建代码块、使用循环、声明和使用几个本地人等等。我们需要等到 .NET 4 出来:)
此外,我正在处理一个已经依赖于 SRE 的代码库。
显然,ILGenerator 做了我需要的一切。但是在操作它时,我会很感激更多的帮助。当我提到 ILGenerator 包装器时,它仍然处于相当低的级别,我想到了一些可以提供以下方法的方法:
// Performs a virtual or direct call on the method, depending if it is a
// virtual or a static one.
Call(MethodInfo methodInfo)
// Pushes the default value of the type on the stack, then emit
// the Ret opcode.
ReturnDefault(Type type)
// Test the object type to emit the corresponding push
// opcode (Ldstr, Ldc_I*, Ldc_R*, etc.)
LoadConstant(object o)
这确实是 3 个幼稚的例子,但足以证明我的期望。我们可以将其视为一组扩展方法,但最好支持条件语句和循环,如RunSharp。事实上,RunSharp 与我想要的非常接近,但它过多地抽象了 ILGenerator 并且没有公开其所有功能。
我不记得在哪里了,但是我已经在一个开源项目中看到过这样的助手。