巧用泛型和Lambda解决只读对象的缓存技巧
/// <summary>
/// 只读缓存辅助
/// </summary>
/// <typeparam name="KeyType">键类型</typeparam>
/// <typeparam name="ValueType">值类型</typeparam>
public static class Cache<KeyType, ValueType>
{
public delegate ValueType GetValue(KeyType key);
private static Dictionary<KeyType, ValueType> data=new Dictionary<KeyType,ValueType>();
/// <summary>
/// 获取缓存中的数据
/// </summary>
/// <param name="key">键</param>
/// <param name="get">Lambda表达式,当缓存不存在时获取值的委托</param>
/// <returns></returns>
public static ValueType Get(KeyType key, GetValue get)
{
if (data.ContainsKey(key))
return data[key];
else
{
ValueType value = get(key);
data.Add(key,value);
return value;
}
}
}
/// 只读缓存辅助
/// </summary>
/// <typeparam name="KeyType">键类型</typeparam>
/// <typeparam name="ValueType">值类型</typeparam>
public static class Cache<KeyType, ValueType>
{
public delegate ValueType GetValue(KeyType key);
private static Dictionary<KeyType, ValueType> data=new Dictionary<KeyType,ValueType>();
/// <summary>
/// 获取缓存中的数据
/// </summary>
/// <param name="key">键</param>
/// <param name="get">Lambda表达式,当缓存不存在时获取值的委托</param>
/// <returns></returns>
public static ValueType Get(KeyType key, GetValue get)
{
if (data.ContainsKey(key))
return data[key];
else
{
ValueType value = get(key);
data.Add(key,value);
return value;
}
}
}
使用例子:
反射MyModel对象所有属性并且缓存
PropertyInfo[] MyProperty = Cache<Type, PropertyInfo[]>.Get(typeof(MyModel), p => p.GetProperties());
www.3kk.com原创
posted on 2009-01-14 15:40 passer.net 阅读(865) 评论(3) 编辑 收藏 举报