如何创建用于表达式构建的静态Lambda? [英] How to create a static lambda for use with expression building?

查看:68
本文介绍了如何创建用于表达式构建的静态Lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从C#6开始,lambdas现在默认为实例方法,并且永远不会是静态的(我认为这意味着它们现在始终可以捕获,我认为这样会更高效[在讨论中似乎更快]).

As of C# 6, lambdas now default to instance methods, and will never be static (which I assume means they always capture now, which I guess is more efficient [seems to be faster given the discussions]).

请参阅此处:和此处: CSC和Roslyn编译器的静态Lambda表达式评估?

这现在导致在创建静态MethodInfos来调用诸如Expression.Convert(Expression, typeof({SomeType}), conversionMethodInfo);

This causes issues now with using lambdas when creating static MethodInfos for calls to expression methods such as Expression.Convert(Expression, typeof({SomeType}), conversionMethodInfo);

那么,执行此操作的新方法是什么?我尝试对lambda使用"static"修饰符,但它不起作用.对于那些无法想象此类代码的人,这可能是一个示例:

So then, what is the new way of doing this? I tried to use the "static" modifier with lambdas and it doesn't work. For those who can't imagine such code, this might be one example:

Func <T1,T2> converter = static v => ConvertT1ToT2(v); // ('T' is whatever type you want)
Expression.Convert(expression, typeof({SomeType}), converter.Method) // (error: converter.Method.IsStatic is false)

是的,显然是行不通的.

Yes, obviously it doesn't work.

推荐答案

如果其他人希望知道,最后,我不得不将我的表达式提升(降级)为表达式增强的函数成员",例如这个:

In case others wish to know, in the end, I had to promote (demote? lol) my expressions to "Expression-bodied function members" instead, like this:

// (class method)
static string _Convert(object obj) => (obj as SomeType)?.SomeProperty ?? ReturnSomethingElse;

然后在我的方法主体中:

then in my method body:

Func<object, string> conversionDelegate = _Convert;
Expression exp = Expression.Convert(expression, typeof(SomeType), conversionDelegate.Method);

此处讨论一些关于非捕获/静态lambda的问题: https://github.com com/dotnet/csharplang/issues/275

Some talk about non-capturing/static lambdas here: https://github.com/dotnet/csharplang/issues/275

这篇关于如何创建用于表达式构建的静态Lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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