How do you use Func<> and Action<> when designing applications?

后端 未结 9 832
情书的邮戳
情书的邮戳 2020-12-22 16:27

All the examples I can find about Func<> and Action<> are simple as in the one below where you see how they technically work but I would like

9条回答
  •  隐瞒了意图╮
    2020-12-22 17:29

    One thing I use it for is Caching of expensive method calls that never change given the same input:

    public static Func Memoize(this Func f)
    {
        Dictionary values;
    
        var methodDictionaries = new Dictionary>();
    
        var name = f.Method.Name;
        if (!methodDictionaries.TryGetValue(name, out values))
        {
            values = new Dictionary();
    
            methodDictionaries.Add(name, values);
        }
    
        return a =>
        {
            TResult value;
    
            if (!values.TryGetValue(a, out value))
            {
                value = f(a);
                values.Add(a, value);
            }
    
            return value;
        };
    }
    

    The default recursive fibonacci example:

    class Foo
    {
      public Func Fibonacci = (n) =>
      {
        return n > 1 ? Fibonacci(n-1) + Fibonacci(n-2) : n;
      };
    
      public Foo()
      {
        Fibonacci = Fibonacci.Memoize();
    
        for (int i=0; i<50; i++)
          Console.WriteLine(Fibonacci(i));
      }
    }
    

提交回复
热议问题