日期:2014-05-18  浏览次数:21105 次

想做一个通用应用程序缓存的方法,但出现是“类型”,但此处被当做“变量”来使用错误,请教大侠们帮帮看看
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>,然后使用单例即可