تحويل المجموعة إلى أسلوب التعبير
-
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 "إلى نوع غير مندوب 'System.Linq.Expressions.Expression <...>'. هل كنت تنوي استدعاء الأسلوب؟"
وحتى لا يكون هناك جملة جيدة لالتقاط جروب طريقة في التعبير؟
وشكرا، آرني
المحلول
وماذا عن هذا؟
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)
}
}
لا تنتمي إلى StackOverflow