转换方法集团表达(Convert Method Group to Expression)

2019-06-23 10:04发布

我想弄清楚的,如果有转换方法组来表达一个简单的语法。 这似乎与lambda表达式很容易,但它并没有转化为方法:

特定

public delegate int FuncIntInt(int x);

以下所有的都是有效的:

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

但如果我尝试用一​​个实例方法一样,它打破了在表达式:

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

无论是过去两年的失败,并编制“不能转换方法组‘AFuncIntInt’非委托类型‘System.Linq.Expressions.Expression <...>’。你有没有打算调用的方法?”

那么,有没有一个好的语法在表达式中捕获方法GROU?

感谢阿恩

Answer 1:

这个怎么样?

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


Answer 2:

也可以用它来办NJection.LambdaConverter一个代表对LambdaExpression转换器库

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


文章来源: Convert Method Group to Expression