How to create a static lambda for use with expression building?

瘦欲@ 提交于 2019-12-05 10:43:06

So then, what is the new way of doing this?

There isn't one. The spec never promised anything about the implementation details of lambda expressions. Which is why you should not depend on them. It's also why What's new in C# 6 does not mention this.

Assuming you need to use Expression.Convert with a custom MethodInfo, then you should promote the lambda into a static method:

private static T2 Converter(T1 v)
{
    return ConvertT1ToT2(v);
}

…

MethodInfo converter =
    typeof(ThisType).GetMethod("Converter", BindingFlags.NonPublic | BindingFlags.Static);
// OR:
MethodInfo converter = ((Func<T1, T2>)Converter).Method;

Expression.Convert(expression, typeof(SomeType), converter)

This way, you're not using a lambda, so it's guaranteed the MethodInfo refers to a static method.

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);

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!