将方法组转换为表达式
我试图弄清楚是否有一个简单的语法可以将方法组转换为表达式。 使用 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<...>'。您打算调用该方法吗?”
那么有没有一个好的语法来捕获表达式中的方法组呢?
谢谢, 阿恩
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用属性而不是方法。
使用上面
I use property instead of method.
Using above
这个怎么样?
How about this?
也可以使用 NJection.LambdaConverter 委托到 LambdaExpression 转换器库来完成此操作
It is also possible to do it using NJection.LambdaConverter a Delegate to LambdaExpression converter Library