将方法组转换为表达式

12

我正在尝试找出是否存在将方法组转换为表达式的简单语法。使用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<...>'。 您打算调用该方法吗?”的错误消息。

那么,有没有一种良好的语法可以在表达式中捕获方法组呢?

谢谢, arne

3个回答

10

这个怎么样?

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

2
你有没有找到更好的语法来处理这个问题?我不完全理解为什么编译器无法确定 Expression<Func<something>> 的方法组,而它却可以确定 Func<something> 的方法组。 - skrebbel
我的假设是foo.AFuncIntInt是一个方法组,而不是表达式,并且没有从方法组到表达式的自动转换,但是有自动转换来接受lambda作为方法组或表达式。 - Arne Claassen

1

还可以使用 NJection.LambdaConverter,它是一个将委托转换为Lambda表达式的库。

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

0

我使用属性而不是方法。

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

使用上述内容

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接