c#:Func <T>参数中的重载决策

moo*_*kid -1 c# generics overloading overload-resolution

写这个功能:

static TResult reduce<TSource, TResult>(ParallelQuery<TSource> source,
                                        Func<TResult> seedFactory,
                                        Func<TResult, TSource, TResult> aggregator) {
    return source.Aggregate(seedFactory, aggregator, aggregator, x => x);
}                
Run Code Online (Sandbox Code Playgroud)

但我得到一个编译错误:

误差为1方法的类型参数"System.Linq.ParallelEnumerable.Aggregate( ,System.Linq.ParallelQuery<TSource>, TAccumulate,, System.Func<TAccumulate,TSource,TAccumulate> )"不能从使用推断.尝试显式指定类型参数.System.Func<TAccumulate,TAccumulate,TAccumulate>System.Func<TAccumulate,TResult>

我想要使​​用的重载是这一个, 而编译器似乎认为它也可以是这个.

我该怎么帮忙呢?

Jon*_*eet 5

问题是你的第三个参数 - 方法声明中的第四个参数.这被宣布为:

// Note: type parameter names as per Aggregate declaration
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc
Run Code Online (Sandbox Code Playgroud)

但是你想要传递一个

// Note: type parameter names as per reduce declaration
Func<TResult, TSource, TResult> aggregator
Run Code Online (Sandbox Code Playgroud)

除非编译器知道TResult可以转换为,否则这是无效的TSource.

基本上,您的方法只采用单个聚合函数 - 如何将累加器到目前为止与另一个源值组合以创建另一个累加器.您想要调用的方法需要另一个函数,它将两个累加器组合在一起以创建另一个累加器.我认为你将不得不在你的方法中采用另一个参数来实现这个目的.