NET标准中CompileToMethod的替代方法 [英] Alternatives of CompileToMethod in .Net Standard

查看:92
本文介绍了NET标准中CompileToMethod的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在将一些使用表达式的库移植到 .Net Core 应用程序,并且遇到一个问题,即我所有的逻辑都基于 LambdaExpression。只是缺少了CompileToMethod 。这是示例代码:

I'm now porting some library that uses expressions to .Net Core application and encountered a problem that all my logic is based on LambdaExpression.CompileToMethod which is simply missing in. Here is sample code:

public static MethodInfo CompileToInstanceMethod(this LambdaExpression expression, TypeBuilder tb, string methodName, MethodAttributes attributes)
{
    ...

    var method = tb.DefineMethod($"<{proxy.Name}>__StaticProxy", MethodAttributes.Private | MethodAttributes.Static, proxy.ReturnType, paramTypes);
    expression.CompileToMethod(method);

    ...
}

是否可以重写它以某种方式使使用表达式生成方法成为可能?我已经可以使用 Emit 来做到这一点,但是它非常复杂,我希望避免使用高级表达式。

Is it possible to rewrite it somehow to make it possible to generate methods using Expressions? I already can do it with Emit but it's quite complex and i'd like to avoid it in favor of high-level Expressions.

我尝试使用 var方法= expression.Compile()。GetMethodInfo(); ,但是在这种情况下,我得到一个错误:

I tried to use var method = expression.Compile().GetMethodInfo(); but in this case I get an error:


System.InvalidOperationException:无法从其他模块导入全局方法或
字段。

System.InvalidOperationException : Unable to import a global method or field from a different module.

我知道我可以手动发出IL,但是我需要将 Expression ->准确地转换为 MethodInfo 绑定到特定的 TypeBuilder 而不是在其上构建 DynamicMethod

I know that I can emit IL manually, but I need exactly convert Expression -> to MethodInfo binded to specific TypeBuilder instead of building myself DynamicMethod on it.

推荐答案

将某些代码移植到netstandard时遇到了相同的问题。我的解决方案是使用Compile方法将lambda编译为Func,将Func存储在添加到动态类型的静态字段中,然后在我的动态方法中,我仅从该静态字段加载并调用Func。这使我可以使用LINQ Expression API而不是反射发射(这会很痛苦)来创建lambda,但仍然可以让我的动态类型实现一个接口(这是我的方案的另一个要求)。

I ran into the same issue when porting some code to netstandard. My solution was to compile the lambda to a Func using the Compile method, store the Func in a static field that I added to my dynamic type, then in my dynamic method I simply load and call the Func from that static field. This allows me to create the lambda using the LINQ Expression APIs instead of reflection emit (which would have been painful), but still have my dynamic type implement an interface (which was another requirement for my scenario).

有点像破解,但它可以工作,并且可能比尝试通过LambdaCompiler重新创建CompileToMethod功能要容易。

Feels like a bit of a hack, but it works, and is probably easier than trying to recreate the CompileToMethod functionality via LambdaCompiler.

这篇关于NET标准中CompileToMethod的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆