首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

想做一个通用应用程序缓存的方法,但出现是“类型”,但此处被当做“变量”来使用异常,请问大侠们帮帮看看

2012-04-01 
想做一个通用应用程序缓存的方法,但出现是“类型”,但此处被当做“变量”来使用错误,请教大侠们帮帮看看C# cod

想做一个通用应用程序缓存的方法,但出现是“类型”,但此处被当做“变量”来使用错误,请教大侠们帮帮看看

C# code
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);    }}


出现“MyCache.GetDataMethod<T>”是“类型”,但此处被当做“变量”来使用这个错误

[解决办法]
new GetDataMethod<T>()
[解决办法]
C# code
    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>,然后使用单例即可

热点排行