Lambda 表达式到 Func<T, TResult>

Lambda expression to Func<T, TResult>

如何将 optionObject.Forms.First(f => f.FormId == formId).MultipleIteration 中的 lambda 表达式写入 Func,所以最后我得到类似

的东西
Func<FormObject, bool> FormID = f => f.formID == passedVal;

然后在第一个表达式上使用它得到类似

的东西
optionObject.Forms.First(FormID).MultipleIteration

我试过了

Func<FormObject, PassedVal, bool> FormID => formID == PassedVal;

但没有用。
请注意lambda 表达式没有任何问题,它工作正常。我只是想创建一个函数来用函数名替换表达式,使代码看起来更短且易于维护。

允许您使用新传递值重用函数体的一个选项是在 class-level 函数中生成 Func<FormData, bool> 个实例:

public static Func<FormObject, bool> CreateFormValidFunc(int validId)
{
    return f => f.formID == validId;
}

那么你可以这样使用它:

optionObject.Forms.First(CreateFormValidFunc(passedVal)).MultipleIteration
optionObject.Forms.First(CreateFormValidFunc(2)).MultipleIteration

一个有趣的旁注是 int Foo => 0; 是 "expression-bodied properties" 语法 (new to C# 6.0),您的尝试可能恰好匹配到足以使错误消息令人困惑。

您可以使用 expression-bodied 方法将验证函数生成器减少为:

public static Func<FormObject, bool> CreateFormValidFunc(int validId) => f => f.formID == validId;

本文post可以帮助您: lambda expression and var keyword

When I try to use var add = (x, y) => x + y; the compiler need to be able to reduce the set to just one type for x and one for y (not exactly true, it might be that both a base class and a derived class would fit) and still even if the compiler could figure out the type for x and y or that you specified the types to let's say int you'd still be left with the fact that both Expression> and Func are possible types for add.

在你的场景中你可以使用这个:

Expression<Func<FormObject, bool>> FormID = f => f.formID == passedVal;