我试图弄清楚是否有将语法组转换为表达式的简单语法。使用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 <!> lt; ... <!> gt; ”。您打算调用该方法吗?<!>“

在表达式中捕获方法组有一个很好的语法吗?

感谢, ·阿尔

有帮助吗?

解决方案

这个怎么样?

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

其他提示

也可以使用 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)
    } 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top