Here is a naive approach of the cache. It is straightforward enough.
public class Cache<TKey, TValue> { Func<TKey, TValue> _resolver; Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>(); public Cache(Func<TKey, TValue> resolver) { _resolver = resolver; } public TValue this[TKey key] { get { TValue value; if (!_cache.TryGetValue(key, out value)) { value = _resolver(key); _cache.Add(key, value); } return value; } } }
And also somewhere in a client code:
class ClientCode { static Cache<TKey, TValue> _cache = new Cache<TKey, TValue>(Resolver); }Where
Resolver
is an user-defined function to get a value from the outer source.