1 //Custom Cache Classes2 Public classCachehelper<t>whereT:class3 {4 Private classEntity5 {6 PublicT value{Get;Set;}7 PublicDateTime Expiretime {Get;Set; }8 }9 Private Static ReadOnlydictionary<string, Entity> dic=Newdictionary<string,entity>();Ten One PublicT This[stringKey] A { - Get - { the if(! Dic.Keys.Contains (Key))return NULL; - vardata =Dic[key]; - if(Data. Expiretime >=DateTime.Now) - { + returndata. Value; - } + Remove (key); A return NULL; at } - } - - Public voidADD (stringKey, T value,intmin) - { - if(Key = =NULL ) { in Throw NewException ("key value cannot be empty"); - } to if(Dic.Keys.Contains (key)) + Throw NewException ("key value already exists"); - the if(Min <=0)Throw NewException ("The expiration time cannot be less than 0 or equal to 0"); * $ varentity =NewEntity {value = value, Expiretime =DateTime.Now.AddSeconds (min)};Panax Notoginseng Dic.add (key, entity); - } the + Public voidUpdate (stringKey, T value,intmin) A { the if(Key = =NULL) + { - Throw NewException ("key value cannot be empty"); $ } $ if(Min <=0)Throw NewException ("The expiration time cannot be less than 0 or equal to 0"); - - varentity =NewEntity {value = value, Expiretime =DateTime.Now.AddSeconds (min)}; theDic[key] =entity; - }Wuyi the Public voidRemove (stringkey) - { Wu if(Key = =NULL) - { About Throw NewException ("key value cannot be empty"); $ } - if(!Dic.Keys.Contains (key)) - Throw NewException ("key value does not exist"); - Dic.remove (key); A } + the}View Code
How to use:
Private cachehelper<_type> cache = new cachehelper<_type>(); if NULL ){//...... 5*); // ......}
11th article Customizing a cache class (very use ~)