将方法组转换为表达式 [英] Convert Method Group to Expression

查看:148
本文介绍了将方法组转换为表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如果有一个简单的语法将方法组转换为表达式。对于lambdas来说看起来很简单,但不能转化为方法:



给定

 public delegate int FuncIntInt(int x); 

以下所有内容均有效:

  Func< int,int> func1 = x => X; 
FuncIntInt del1 = x => X;
表达式< Func< int,int>> funcExpr1 = x => X;
表达式< FuncIntInt> delExpr1 = x => X;

但是,如果我尝试与实例方法相同,则会在表达式中分解:

  Foo foo = new Foo(); 
Func< int,int> func2 = foo.AFuncIntInt;
FuncIntInt del2 = foo.AFuncIntInt;
表达式< Func< int,int>> funcExpr2 = foo.AFuncIntInt; //不编译
表达式&FunCIntInt> delExpr2 = foo.AFuncIntInt; //不编译

最后两个都无法使用无法转换方法组AFuncIntInt '到非委托类型'System.Linq.Expressions.Expression< ...>'你打算调用该方法吗?



那么有一个很好的谢谢,b
$ b

解决方案

这个怎么样?

 表达式< Func< int,int>> funcExpr2 =(pArg)=> foo.AFuncIntInt(PARG); 
表达式< FuncIntInt> delExpr2 =(pArg)=> foo.AFuncIntInt(PARG);


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

解决方案

How about this?

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

这篇关于将方法组转换为表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆