首页 > 代码库 > 第十一篇 自定义一个缓存类(甚用~)

第十一篇 自定义一个缓存类(甚用~)

 1 //自定义缓存类 2    public class CacheHelper<T>    where T:class 3     { 4         private class Entity 5         { 6             public T Value{get;set;} 7             public DateTime Expiretime { get; set; } 8         } 9         private static readonly Dictionary<string, Entity> Dic=new Dictionary<string,Entity>();10 11         public T this[string key]12         {13             get14             {15                 if (!Dic.Keys.Contains(key)) return null;16                 var data =http://www.mamicode.com/ Dic[key];17                 if (data.Expiretime >= DateTime.Now)18                 {19                     return data.Value;20                 }21                 Remove(key);22                 return null;23             }24         }25 26         public void Add(string key, T value, int min)27         {28              if( key == null ) {29                  throw new Exception("键值不能为空");30             }31              if (Dic.Keys.Contains(key))32                  throw new Exception("键值已经存在");33 34              if (min <= 0) throw new Exception("过期时间不能小于0或等于0");35 36              var entity = new Entity {Value = http://www.mamicode.com/value, Expiretime = DateTime.Now.AddSeconds(min)};37             Dic.Add(key, entity);38         }39 40         public void Update(string key, T value, int min)41         {42             if (key == null)43             {44                 throw new Exception("键值不能为空");45             }46             if (min <= 0) throw new Exception("过期时间不能小于0或等于0");47 48             var entity = new Entity {Value = http://www.mamicode.com/value, Expiretime = DateTime.Now.AddSeconds(min)};49             Dic[key] = entity;50         }51 52         public void Remove(string key)53         {54             if (key == null)55             {56                 throw new Exception("键值不能为空");57             }58             if (!Dic.Keys.Contains(key))59                 throw new Exception("键值不存在");60             Dic.Remove(key);61         }62 63     }
View Code

 使用方法:

private CacheHelper<_type> cache =            new CacheHelper<_type>();if (cache[key] == null){//......   cache.Add(period + userNum, listInfo, 5*60);//......}

 

第十一篇 自定义一个缓存类(甚用~)