using System;
using System.Collections.Generic;
using JD.Kernel.StaticHelpers;
namespace JD.Collections
{
///
/// Base framework for a keyed cache.
///
public class KeyedCacheBase : IEnumerable>
{
private Dictionary m_cache = new Dictionary();
///
/// Returns the value for the key, (if not cached, will use the provider).
///
///
///
///
protected TValue this[TKey key, Converter provider]
{
get
{
Throw.IfNull(provider, "provider");
TValue result;
lock (m_cache)
{
if (!m_cache.TryGetValue(key, out result))
{
result = provider(key);
if (!m_cache.ContainsKey(key))
{
m_cache.Add(key, result);
}
}
}
return result;
}
}
///
/// Clears the cache.
///
public void Clear()
{
m_cache.Clear();
}
///
/// Adds in the cache
///
///
///
public void Add(TKey key, TValue value)
{
m_cache.Add(key, value);
}
///
/// True if the key is cached.
///
///
///
public bool Contains(TKey key)
{
return m_cache.ContainsKey(key);
}
///
/// Lists all the values.
///
public IEnumerable Values
{
get { return m_cache.Values; }
}
#region IEnumerable> Members
///
/// Enumerates the entries.
///
///
public IEnumerator> GetEnumerator()
{
return m_cache.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return m_cache.GetEnumerator();
}
#endregion
}
}