FunctionCache<T, TResult>
A maximális teljesítmény eléréséhez általában elengedhetetlen a gyorsítótár. Nézzük meg, hogyan lehet ezt megoldani úgy, hogy ne csak a megoldás, hanem a használat is a lehető legegyszerűbb legyen.
/// <summary> /// Represents a class, that caches the return value of a specified function. /// </summary> public class FunctionCache<T, TResult> { /// <summary> /// Initializes a new instance of the FunctionCache<T, TResult> class. /// </summary> /// <param name="func"></param> public FunctionCache(Func<T, TResult> func) { this.Function = func; this.Cache = new Dictionary<T, TResult>(); } protected IDictionary<T, TResult> Cache; /// <summary> /// Gets the function to be cached. /// </summary> public Func<T, TResult> Function { get; protected set; } /// <summary> /// Invokes the function and adds its return value to the cache. /// </summary> /// <param name="arg"></param> /// <returns></returns> public TResult Invoke(T arg) { if (!this.Cache.ContainsKey(arg)) this.Cache.Add(arg, this.Function(arg)); return this.Cache[arg]; } /// <summary> /// Clears cache. /// </summary> public void Reset() { this.Cache.Clear(); } }