gpt4 book ai didi

C#聚合函数定义解释

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:18 25 4
gpt4 key购买 nike

Enumerable.Aggregate 有 3 个重载版本。我找不到此函数的任何重载版本来匹配 official example 中使用的版本.

public static TSource Aggregate<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func
)

上面的定义和这个官方例子完全不同:

string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words.
string[] words = sentence.Split(' ');

// Prepend each word to the beginning of the
// new sentence to reverse the word order.
string reversed = words.Aggregate((workingSentence, next) =>
next + " " + workingSentence);

Console.WriteLine(reversed);

// This code produces the following output:
//
// dog lazy the over jumps fox brown quick the

这里有聚合函数的 3 个重载版本:

public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func);

public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);

public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector);

它们都不符合上例中使用的函数。官方文档有错吗?或者我错过了什么?请帮我弥合三个版本的函数定义和这个官方示例之间的差距。

如何理解函数定义?

最佳答案

public static TSource Aggregate<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func
)

这个其实是官方例子中用的:

string reversed = words.Aggregate((workingSentence, next) =>
next + " " + workingSentence);

一些可能会让您感到困惑的部分是:

  1. this source 前面的关键字参数将其标识为扩展方法,这意味着上面的代码是语法糖:

    string reversed = Enumerable.Aggregate(words, (workingSentence, next) =>
    next + " " + workingSentence);
  2. TSource是一个通用参数,在本例中用 string 代替因为编译器能够根据 words 的事实推断这种类型是一个 IEnumerable<string> .

  3. Func<TSource, TSource, TSource>是一个通用委托(delegate),表示一个函数,该函数接受两个参数(前两个 TSource s),并返回一个 TSource .这与 Action<TSource, TSource> 形成对比,它将采用两个参数并且不返回值。这些类型中的任何一种都可以用形式为 (param1, param2) => expression 的 lambda 表达式表示。 .

关于C#聚合函数定义解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43194098/

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