11

我试图弄清楚是否有将方法组转换为表达式的简单语法。使用 lambdas 似乎很容易,但它不能转化为方法:

给定

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<...>'。您打算调用该方法吗?”

那么有没有一种很好的语法来捕获表达式中的方法组呢?

谢谢,阿恩

4

3 回答 3

9

这个怎么样?

  Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);
  Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);
于 2009-06-16T22:01:49.650 回答
0

也可以使用NJection.LambdaConverter a Delegate to 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)
    } 
}
于 2013-12-21T19:19:17.407 回答
0

我使用属性而不是方法。

public class MathLibrary
{
    public Expression<Func<int, int>> AddOne {  
        get {   return input => input + 1;} 
    }
}

使用上面

在此处输入图像描述

于 2020-03-17T23:15:42.440 回答