简体   繁体   中英

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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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