日期:2014-05-18 浏览次数:21324 次
public static class MyCache
{
//获取数据的方法
public delegate T GetDataMethod<T>();
public static T GetCache<T>(string key)
{
if (HttpRuntime.Cache[key] == null)
{
T list = [color=#FF0000]GetDataMethod<T>()[/color];
HttpRuntime.Cache.Add(key, list, null, DateTime.Now.AddMinutes(10),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
return list;
}
return (T)HttpRuntime.Cache[key];
}
/// <summary>
/// 移除应用程序缓存
/// </summary>
/// <param name="key">值</param>
public static void RemoveCacheByKey(string key)
{
HttpRuntime.Cache.Remove(key);
}
}
public static class MyCache
{
//获取数据的方法
public delegate T GetDataMethod<T>();
public static T GetCache<T>(string key)
{
if (HttpRuntime.Cache[key] == null)
{
GetDataMethod<T> del = new GetDataMethod<T>();
T list = del();
//T list = GetDataMethod<T>();
HttpRuntime.Cache.Add(key, list, null, DateTime.Now.AddMinutes(10),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
return list;
}
return (T)HttpRuntime.Cache[key];
}
/// <summary>
/// 移除应用程序缓存
/// </summary>
/// <param name="key">值</param>
public static void RemoveCacheByKey(string key)
{
HttpRuntime.Cache.Remove(key);
}
}
------解决方案--------------------
问题太多。
1.delegate定义了类型你把类型当变量使用了,你需要实例化一个GetDataMethod<T>
2.模板定义使用错误。GetDataMethod<T> 和 GetCache<T>中的类型T不是同一个类型。
解决办法一个是使用object返回对象不使用T
另一个是在类上定义T:MyCache<T>,然后使用单例即可