简体   繁体   English

C#中的重载分辨率:Func <T> 参数

[英]overload resolution in c#: Func<T> parameter

Writing this function: 编写此功能:

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

but I get a compilation error: 但出现编译错误:

Error 1 The type arguments for method 'System.Linq.ParallelEnumerable.Aggregate( System.Linq.ParallelQuery<TSource> , TAccumulate , System.Func<TAccumulate,TSource,TAccumulate> , System.Func<TAccumulate,TAccumulate,TAccumulate> , System.Func<TAccumulate,TResult> )' cannot be inferred from the usage. 错误1方法'System.Linq.ParallelEnumerable.Aggregate( System.Linq.ParallelQuery<TSource>TAccumulateSystem.Func<TAccumulate,TSource,TAccumulate>System.Func<TAccumulate,TAccumulate,TAccumulate>System.Func<TAccumulate,TResult> )'不能从用法中推断出来。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

The overload I want to use is this one while the compiler seems to think it can be this one too. 我想使用的重载就是这一点,而编译器似乎也认为也可以是这一点

How can I help it? 我该如何协助?

The problem is your third argument - the fourth parameter for in the method declaration. 问题是您的第三个参数-方法声明中的第四个参数。 That's declared as: 声明为:

// Note: type parameter names as per Aggregate declaration
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc

But you're trying to pass in a 但是您正在尝试传递

// Note: type parameter names as per reduce declaration
Func<TResult, TSource, TResult> aggregator

That's not valid unless the compiler knows that TResult is convertible to TSource . 除非编译器知道TResult可转换为TSource ,否则这是无效的。

Basically, your method only takes a single aggregation function - how to combine the accumulator so far with another source value to create another accumulator. 基本上,您的方法仅采用单个聚合函数-到目前为止如何将累加器与另一个源值组合以创建另一个累加器。 The method you want to call needs another function which combines two accumulators together to create another accumulator. 您要调用的方法需要另一个函数,该函数将两个累加器组合在一起以创建另一个累加器。 I think you're going to have to take another parameter in your method for this to work. 我认为您必须在方法中采用另一个参数才能使此方法起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM