Why should I explicitly specify type arguments for Func parameters?

I am writing a simple helper Memoizethat allows you to use caching methods rather than calculating them every time. However, when I try to pass a method to Memoize, the compiler cannot determine the type arguments. Aren't they obvious from my method signature? Is there any way around this?

Code example:

using System;
using System.Collections.Concurrent;

public static class Program
{
    public static Func<T, V> Memoize<T, V>(Func<T, V> f) => a =>
        new ConcurrentDictionary<T, V>().GetOrAdd(a, f);

    // This is the method I wish to memoize
    public static int DoIt(string a) => a.Length;        

    static void Main()
    {
        // This line fails to compile (see later for error message)
        var cached1 = Memoize(DoIt);

        // This works, but is ugly (and doesn't scale to lots of type parameters)
        var cached2 = Memoize<string, int>(DoIt);
    }
}

Error message:

error CS0411: The type arguments for method 'Program.Memoize<T, V>(Func<T, V>)'
cannot be inferred from the usage. Try specifying the type arguments explicitly.
+4
source share
1 answer

Is the signature compatible DoIt()with Func<string, int>?

Yes it is. It is perfect to convert it to this particular type, for example, for example:

Func<string, int> func = DoIt;
var cachedDoit = Memoize(func);

, , , . DoIt , . , ... .

, LINQ, foo.Select(SomeMethodGroup), . , , .

, # ... , . 7.5.2 # 5, - , , , .

+5

Source: https://habr.com/ru/post/1695232/


All Articles