Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyCalculator
- {
- private Memoizer<MyCalculator> _memoizer;
- public MyCalculator()
- {
- _memoizer = new Memoizer(this);
- }
- private string MyNotOptomizedMethod(string arg1, string arg2, int arg3)
- {
- //calculating...
- }
- public string MyMethod(string arg1, string arg2, int arg3) =>
- _memoizer.Memo<string>(nameof(MyNotOptomizedMethod), arg1, arg2, arg3);
- }
- public class Memoizer<TState>
- where TState: class, new()
- {
- private TState _state;
- private Type _stateType;
- private Dictionary<(string methodName, object[] args), object> _cache = new Dictionary<(string methodName, object[] args), object>();
- public Memoizer(TState state)
- {
- _state = state;
- _stateType = state.getType();
- }
- public TResult Memo<TResult>(string methodName, params object[] args)
- {
- if (_cache.TryGetValue((methodName, args), out var result)
- {
- return (TResult)result;
- }
- var result = _stateType.GetMethod(methodName).Invoke(_state, args);
- _cache[(methodName, args)] = result;
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement