[英]Generic wrapper for System.Web.Caching.Cache functions
我已經創建了一個使用Cache對象的通用包裝器:
public class Cache<T> where T : class
{
public Cache Cache {get;set;}
public CachedKeys Key {get;set;}
public Cache(Cache cache, CachedKeys key){
Cache = cache;
Key = key;
}
public void AddToCache(T obj){
Cache.Add(Key.ToString(),
obj,
null,
DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
public bool TryGetFromCache(out T cachedData) {
cachedData = Cache[Key.ToString()] as T;
return cachedData != null;
}
public void RemoveFromCache() {
Cache.Remove(Key.ToString()); }
}
CachedKeys枚舉只是可用於緩存數據的鍵列表。
麻煩的是,稱之為非常令人費解:
var cache = new Cache<MyObject>(Page.Cache, CachedKeys.MyKey);
MyObject myObject = null;
if(!cache.TryGetFromCache(out myObject)){
//get data...
cache.AddToCache(data); //add to cache
return data;
}
return myObject;
我只在緩存中存儲每個對象的一個實例。
因此,有什么方法可以創建一個擴展方法來接受Cache的對象類型並使用(通過Reflection)將其Name
作為緩存鍵?
public static Cache<T> GetCache(this Cache cache, Type cacheType){
Cache<cacheType> Cache = new Cache<cacheType>(cache, cacheType.Name);
}
當然,這里有兩個錯誤:
這顯然不是正確的方法,但我認為我會展示我的工作。 有人可以指導我朝正確的方向發展嗎?
我最終使用了通用擴展方法:
public static class CacheExtensions
{
public static void Remove<T>(this Cache cache) where T : class
{
cache.Remove(typeof(T).Name);
}
public static void AddToCache<T>(this Cache cache, object item) where T : class
{
T outItem = null;
if (cache.TryGetItemFromCache<T>(out outItem))
throw new ArgumentException("This item is already in the cache");
cache.Insert(typeof(T).Name,
item,
null,
DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
public static bool TryGetItemFromCache<T>(this Cache cache, out T item) where T : class
{
item = cache.Get(typeof(T).Name) as T;
return item != null;
}
}
被稱為:
MyObject myObject = null;
if(!Cache.TryGetItemFromCache(out myObject)){
//get data
Cache.AddToCache<MyObject>(data);
}
and..
Cache.Remove<MyObject>();
怎么樣:
public static Cache<T> GetCache<T>(this Cache cache)
{
return new Cache<T>(cache, typeof(T).Name);
}
這當然必須在另一個類中定義。
我認為需要更改以下方法:
public static bool TryGetItemFromCache<T>(this Cache cache, out T item) where T : class
{
item = cache.Get(typeof(T).Name) as T;
return item != null;
}
如果項目不在緩存中,則不要將項目放在緩存中以供以后使用或以后檢索。
謝謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.