首页 > 其他 > 详细

对Cache类的一个泛型包装CacheHelper

时间:2014-02-12 15:20:11      阅读:312      评论:0      收藏:0      [点我收藏+]

对Cache类的一个泛型包装


public static class CacheHelper
    {
        public class Settings
        {
            public string Key { get; set; }
            /// <summary>
            /// Seconds
            /// </summary>
            public int Duration { get; set; }

            public Settings(string key,object o=null)
            {
                Key = key;
                if (o != null)
                {
                    Key = BuildKey(o, key);
                }
#if DEBUG
                Duration = 1;
#else
                Duration = 60;
#endif
            }
        }

        public static string BuildKey<T>(T t,string baseKey=null)
        {
            var sbKey = new StringBuilder(baseKey);
            foreach (PropertyInfo pi in t.GetType().GetProperties())
            {
                sbKey.AppendFormat("{0}{1}", pi.Name, pi.GetValue(t, null));
            }
            return sbKey.ToString();
        }
        public static Cache CurrentCache
        {
            get
            {
                return HttpContext.Current != null ? HttpContext.Current.Cache : HttpRuntime.Cache;
            }
        }

        public static T GetCache<T>(Settings settings)
        {
            if (CurrentCache[settings.Key] != null)
            {
                return (T)CurrentCache[settings.Key];
            }
            return default(T);
        }
        public static T BuildCache<T>(T t, Settings settings)
        {
            if (CurrentCache[settings.Key] != null)
            {
                return (T)CurrentCache[settings.Key];
            }
            CurrentCache.Insert(settings.Key, t, null, DateTime.Now.AddSeconds(settings.Duration),
                TimeSpan.Zero);
            return t;
        }
    }


对Cache类的一个泛型包装CacheHelper

原文:http://blog.csdn.net/leewhoee/article/details/19106913

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!