对Cache类的一个泛型包装CacheHelper

对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;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值