代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Common.Utils { /// <summary> /// 缓存 /// </summary> public static class CacheHelper { /// <summary> /// 获取缓存 /// </summary> public static object Get(string cacheKey) { return HttpRuntime.Cache[cacheKey]; } /// <summary> /// 设置缓存 /// </summary> public static void Set(string cacheKey, object value) { HttpRuntime.Cache.Insert(cacheKey, value); } /// <summary> /// 添加缓存 /// </summary> public static void Set<T>(string cacheKey, object value) { Type type = typeof(T); string tableName = type.Name; if (HttpRuntime.Cache[tableName] == null) { Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add(cacheKey, value); HttpRuntime.Cache.Insert(tableName, dic); } else { Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName]; if (dic.Keys.Contains<string>(cacheKey)) { dic[cacheKey] = value; } else { dic.Add(cacheKey, value); } HttpRuntime.Cache[tableName] = dic; } } /// <summary> /// 获取缓存 /// </summary> public static object Get<T>(string cacheKey) { Type type = typeof(T); string tableName = type.Name; if (HttpRuntime.Cache[tableName] != null) { Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName]; if (dic.Keys.Contains<string>(cacheKey)) { return dic[cacheKey]; } } return null; } /// <summary> /// 删除缓存 /// </summary> public static void Remove<T>() { HttpRuntime.Cache.Remove(typeof(T).Name); } } }