Can I memoize a Generic Method?

2020-06-29 08:15发布

问题:

I have 2 expensive Generic methods:

  public T DoStuff<T>()
  {
      //return depends on T.
  }

  public T DoStuffBasedOnString<T>(string input)
  {
      //return depends on T.
  }

Their return values can never vary for a given Type and string.

Is it possible to memoize these functions?


My starting point is a memoize function taken from here: https://www.aleksandar.io/post/memoization/

public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> f)
{
    var cache = new ConcurrentDictionary<T, TResult>();
    return a => cache.GetOrAdd(a, f);
}