Advertisement
MrModest

Memoizer.cs

May 20th, 2020
1,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. public class MyCalculator
  2. {
  3.     private Memoizer<MyCalculator> _memoizer;
  4.    
  5.     public MyCalculator()
  6.     {
  7.         _memoizer = new Memoizer(this);
  8.     }
  9.    
  10.     private string MyNotOptomizedMethod(string arg1, string arg2, int arg3)
  11.     {
  12.         //calculating...
  13.     }
  14.    
  15.     public string MyMethod(string arg1, string arg2, int arg3) =>
  16.         _memoizer.Memo<string>(nameof(MyNotOptomizedMethod), arg1, arg2, arg3);
  17. }
  18.  
  19. public class Memoizer<TState>
  20.     where TState: class, new()
  21. {
  22.     private TState _state;
  23.    
  24.     private Type _stateType;
  25.    
  26.     private Dictionary<(string methodName, object[] args), object> _cache = new Dictionary<(string methodName, object[] args), object>();
  27.    
  28.     public Memoizer(TState state)
  29.     {
  30.         _state = state;
  31.         _stateType = state.getType();
  32.     }
  33.    
  34.     public TResult Memo<TResult>(string methodName, params object[] args)
  35.     {
  36.         if (_cache.TryGetValue((methodName, args), out var result)
  37.         {
  38.             return (TResult)result;
  39.         }
  40.        
  41.         var result = _stateType.GetMethod(methodName).Invoke(_state, args);
  42.        
  43.         _cache[(methodName, args)] = result;
  44.        
  45.         return result;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement