如何在asp.net中使用System.Web.Caching?

17

我有一个类,看起来像这样:

using System.Collections.Generic;
using System.Web.Caching;

public static class MyCache
{
    private static string cacheKey = "mykey";

    public static Dictionary<string, bool> GetCacheValue(bool bypassCache)
    {
        var settings = Cache[cacheKey] as Dictionary<string, bool>; // error on this line

        // ...etc...

        return settings
    }
}

我遇到的问题是这个代码无法编译。编译器显示无法像我当前的使用方式那样使用Cache。以下是错误信息:

'System.Web.Caching.Cache' is a 'type' but is used like a 'variable'

这让我感到困惑。我已经在谷歌上搜索了ASP.NET Cache API,并找到许多使用Cache的示例。以下是其中的一个示例:

// http://www.4guysfromrolla.com/articles/100902-1.aspx
value = Cache("key")

      - or -

value = Cache.Get("key")

当我尝试使用 Cache.Get() 时,出现了另一个错误,表明它不是静态方法。

显然,我需要初始化 Cache 的一个实例。这是使用此 API 的正确方式吗?后续问题是,缓存的信息是否跨实例保留?

谢谢您的帮助。


6
使用 HttpRuntime.Cache 来获取 Cache 实例。 - MarcinJuraszek
1个回答

23

System.Web.Caching.Cache 是一个类 - 你会看到人们使用名为 Cache 的属性,它是 System.Web.Caching.Cache 的一个实例。 如果你在没有提供 Cache 属性的类之外使用它,请使用 System.Web.HttpRuntime.Cache 访问:

var settings = System.Web.HttpRuntime.Cache[cacheKey] as Dictionary<string, bool>;

2
太棒了。当有简单的解释时,我很喜欢它! - quakkels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接