JD2022-TU1/main/tools/framework/JD.Collections/KeyedCacheBase.cs

100 lines
No EOL
2.6 KiB
C#

using System;
using System.Collections.Generic;
using JD.Kernel.StaticHelpers;
namespace JD.Collections
{
/// <summary>
/// Base framework for a keyed cache.
/// </summary>
public class KeyedCacheBase<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private Dictionary<TKey, TValue> m_cache = new Dictionary<TKey, TValue>();
/// <summary>
/// Returns the value for the key, (if not cached, will use the provider).
/// </summary>
/// <param name="key"></param>
/// <param name="provider"></param>
/// <returns></returns>
protected TValue this[TKey key, Converter<TKey, TValue> 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;
}
}
/// <summary>
/// Clears the cache.
/// </summary>
public void Clear()
{
m_cache.Clear();
}
/// <summary>
/// Adds in the cache
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(TKey key, TValue value)
{
m_cache.Add(key, value);
}
/// <summary>
/// True if the key is cached.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Contains(TKey key)
{
return m_cache.ContainsKey(key);
}
/// <summary>
/// Lists all the values.
/// </summary>
public IEnumerable<TValue> Values
{
get { return m_cache.Values; }
}
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
/// <summary>
/// Enumerates the entries.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return m_cache.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return m_cache.GetEnumerator();
}
#endregion
}
}