방법 그룹을 표현식으로 변환합니다
-
05-07-2019 - |
문제
메소드 그룹을 표현식으로 변환하기위한 간단한 구문이 있는지 알아 내려고합니다. 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'를 비 지질 유형으로 변환 할 수 없습니다. llinq.expressions.expressions.expression <...> '로 컴파일하지 못합니다.이 메소드를 호출하려고 했습니까?"
그렇다면 표현식에서 방법 GROU를 캡처하기위한 좋은 구문이 있습니까?
고마워요, 아네
해결책
이건 어때?
Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);
Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);
다른 팁
그것을 사용하는 것도 가능합니다 njection.lambdaconverter Lambdaexpression Converter 라이브러리 대의원
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)
}
}
제휴하지 않습니다 StackOverflow