c# - 我们如何在 C# 中解释 => Something => Something2 => Something3

标签 c# function lambda operator-keyword

我正在读 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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator但文档中的demo并不像上面的代码那么复杂。

最佳答案

这里的 => 意味着不同的东西,但一般来说,每一个都表示一个 lambda 匿名函数(带有 opt.closure),它被传递到某处 - 通常作为函数调用中的参数。

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

First => 是方法体 (FailFast) 的简写形式,用于在小方法中跳过编写 { } 以提高“可读性”(此处:值得怀疑)。
第二个 => 是一个 lambda,创建为 FailFast 的返回值。
第三个 => 是一个 lambda,作为参数传递给 Aggregate()。
第四个 => 是一个 lambda,作为参数传递给 Bind()。

添加一些括号并添加顶级函数括号以使其更加明显:

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 范围。

关于c# - 我们如何在 C# 中解释 => Something => Something2 => Something3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72143500/

相关文章:

c# - ASP.NET MVC/C# 2010 最佳实践?

c# - 如何在 SpannableString Android 中设置不透明度/alpha

Java lambda 表达式、强制转换和比较器

c# - 没有声明的 Lambda 表达式?

c++ - 根据消息调用函数

java - 为重用声明一个静态 Java lambda 是否更有效?

c# - 解码查询参数值中带有特殊和或 + 字符的 Url

c# - 将 Gmail 附件拖到 c# winform

c - 错误: a parameter list without types is only allowed in a function definition

c - 带有 C 语言函数的简单无限循环