I`ve got this class with this method where I require to support for both reference types and value types but I do not know how exactly how to perform this. Any help would be much appreciated.
public static class CacheHelper<T>
{
public static T Get(string key, Func<T> function) {
var obj = (T)HttpContext.Current.Cache[key];
if (obj == null)
{
obj = function.Invoke();
HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(3),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
return (T)obj;
}
}
I think if you remove the cast to T
on this line var obj = HttpContext.Current.Cache[key];
you should be fine.
public static class CacheHelper<T>
{
public static T Get(string key, Func<T> function) {
var obj = HttpContext.Current.Cache[key];
if (obj == null)
{
obj = function.Invoke();
HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(3),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
return (T)obj;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.