Convert Method Group to Expression

房东的猫 提交于 2019-12-01 15:03:47

问题


I'm trying to figure out of if there is a simple syntax for converting a Method Group to an expression. It seems easy enough with lambdas, but it doesn't translate to methods:

Given

public delegate int FuncIntInt(int x);

all of the below are valid:

Func<int, int> func1 = x => x;
FuncIntInt del1 = x => x;
Expression<Func<int, int>> funcExpr1 = x => x;
Expression<FuncIntInt> delExpr1 = x => x;

But if i try the same with an instance method, it breaks down at the Expressions:

Foo foo = new Foo();
Func<int, int> func2 = foo.AFuncIntInt;
FuncIntInt del2 = foo.AFuncIntInt;
Expression<Func<int, int>> funcExpr2 = foo.AFuncIntInt; // does not compile
Expression<FuncIntInt> delExpr2 = foo.AFuncIntInt;      //does not compile

Both of the last two fail to compile with "Cannot convert method group 'AFuncIntInt' to non-delegate type 'System.Linq.Expressions.Expression<...>'. Did you intend to invoke the method?"

So is there a good syntax for capturing a method grou in an expression?

thanks, arne


回答1:


How about this?

  Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);
  Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);



回答2:


It is also possible to do it using NJection.LambdaConverter a Delegate to LambdaExpression converter Library

public class Program
{
    private static void Main(string[] args) {
       var lambda = Lambda.TransformMethodTo<Func<string, int>>()
                          .From(() => Parse)
                          .ToLambda();            
    }   

    public static int Parse(string value) {
       return int.Parse(value)
    } 
}


来源:https://stackoverflow.com/questions/1004156/convert-method-group-to-expression

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