我们如何在 C# 中解释 => something => something2 => something3

how do we interpret => something => something2 => something3 in C#

我正在阅读 Enrico Buonanno 所著的《C# 函数式编程》一书

public static Validator<T> FailFast<T>
   (IEnumerable<Validator<T>> validators)
   => t
   => validators.Aggregate(Valid(t), (acc, validator) => acc.Bind(_ => validator(t)));

以上代码原文为:

The fail-fast strategy is easier to implement: Every validator returns a Validation, and Validation exposes a Bind function that only applies the bound function if the state is Valid (just like Option and Either), so we can use Aggregate to traverse the list of validators and Bind each validator to the running result.

The FailFast function takes a list of Validators and returns a Validator: a function that expects an object of type T to validate. On receiving the valid t, it traverses the list of validators using Valid(t) as accumulator (if the list of validators is empty, then t is valid) and applies each validator in the list to the accumulator with Bind.

三个=>标志。这让我很难很好地理解代码。有谁熟悉 => 运算符并能用通俗易懂的英语解释一下吗?非常感谢。

我还在文档中检查了 => 运算符。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator但是文档中的demo没有上面的代码那么复杂

这里的 => 有不同的含义,但一般来说,每个都表示一个 lambda 匿名函数(带有可选闭包)传递到某处 - 通常作为函数调用中的参数。

因此,从像 类 这样的大块明显的代码和顶级方法开始,找到指示函数调用的强制性 (),它可能会更容易掌握。

First => 是一种 shorthand 形式的方法体 (FailFast) 以跳过 'readability' 的小方法中编写 { } (这里:值得怀疑)。
第二个 => 是一个 lambda,创建为 FailFast 的 return 值。
第三个 => 是一个 lambda,作为参数传递给 Aggregate()。
第四个 => 是一个 lambda,作为参数传递给 Bind()。

添加一些括号并添加 top-level 函数括号以使其更加可见:

public static Validator<T> FailFast<T>(IEnumerable<Validator<T>> validators)
{
    return t => validators.Aggregate(Valid(t), ..secondparam..);
}

第二个参数是:

(acc, validator) => acc.Bind(...anotherparam...)

另一个参数是:

_ => validator(t)

其中 t 来自 return t=> 中的 lambda 范围。