gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:12:14 24 4
gpt4 key购买 nike

我正在读 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com