Dictionary实现的缓存类Cache
最近用到缓存,所以就自己动手写了一个简单的Cache.
命名空间JChen.Ext有这个方法:
/// <summary>
/// 是否为NULL或者空
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this string str)
{
if (str == null || str.Trim() == "")
{
return true;
}
return false;
}
using System;
using System.Collections.Generic;
using JChen.Ext;
namespace JChen.Caching
{
/// <summary>
/// 缓存
/// </summary>
/// <typeparam name="T"></typeparam>
public class Cache<T>
{
/// <summary>
/// 锁
/// </summary>
private static object lockObj = new object();
/// <summary>
/// 默认Cache
/// </summary>
private static Cache<T> _default = new Cache<T>(true);
/// <summary>
/// 每个实例的缓存
/// </summary>
private Dictionary<string, T> instanceCache = null;
/// <summary>
/// 默认的缓存
/// </summary>
private static Dictionary<string, T> defaultCache = new Dictionary<string, T>();
/// <summary>
/// 缓存
/// </summary>
public Cache()
{
instanceCache = new Dictionary<string, T>();
}
/// <summary>
/// 私有构造,区别于Cache(),只是为了实例化_default;
/// 对于默认的缓存,不需要且不能实例化instanceCache
/// </summary>
/// <param name="isDefualt"></param>
private Cache(bool isDefualt)
{
}
/// <summary>
/// 相对于T的默认缓存实例
/// 特别注意:对于相同的类型T,Default是同一个对象
/// </summary>
public static Cache<T> Default { get { return _default; } }
/// <summary>
/// 设置或获取缓存数据
/// </summary>
/// <param name="key">键,不能为空</param>
/// <returns>如果键为空,返回值为类型T的默认值</returns>
public T this[string key]
{
get
{
if (instanceCache != null)
{
if (instanceCache.ContainsKey(key))
{
return instanceCache[key];
}
}
else
{
if (defaultCache.ContainsKey(key))
{
return defaultCache[key];
}
}
return default(T);
}
set
{
if (key.IsNullOrEmpty())
{
throw new ArgumentNullException("key", "键不能为空!");
}
if (instanceCache != null)
{
if (instanceCache.ContainsKey(key))
{
instanceCache[key] = value;
}
else
{
lock (lockObj)
{
instanceCache.Add(key, value);
}
}
}
else
{
if (defaultCache.ContainsKey(key))
{
defaultCache[key] = value;
}
else
{
lock (lockObj)
{
defaultCache.Add(key, value);
}
}
}
}
}
/// <summary>
/// 缓存数量
/// </summary>
public int Count
{
get
{
if (instanceCache != null)
{
return instanceCache.Count;
}
else
{
return defaultCache.Count;
}
}
}
/// <summary>
/// 移除指定键的缓存值
/// </summary>
/// <param name="key">键,不能为空</param>
/// <returns></returns>
public bool Remove(string key)
{
if (key.IsNullOrEmpty())
{
return false;
}
if (instanceCache != null)
{
if (instanceCache.ContainsKey(key))
{
return instanceCache.Remove(key);
}
}
else
{
if (defaultCache.ContainsKey(key))
{
return defaultCache.Remove(key);
}
}
return false;
}
/// <summary>
/// 清空缓存
/// </summary>
public void Clear()
{
if (instanceCache != null)
{
instanceCache.Clear();
}
else
{
defaultCache.Clear();
}
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。