如何检查MemoryCache中是否存在密钥

时间:2013-07-25 11:29:24

标签: c# .net caching

我需要检查MemoryCache中是否存在密钥。但是没有Keys集合或类似的东西可用。

如果存在某个键,我不需要与键关联的对象只有true或false。

我知道我可以尝试.Get(键),但我不需要该对象。这是唯一的方法吗?

2 个答案:

答案 0 :(得分:8)

使用bool Contains(string key, string regionName)方法。

<强> MSDN

  

确定缓存中是否存在缓存条目。   返回值类型:System.Boolean如果缓存包含缓存,则为true   密钥与密钥匹配的条目;否则,假    MemoryCache.Contains Method (String, String) MSDN

答案 1 :(得分:0)

你应该检查缓存是否不是Null&amp;检查密钥是否存在的帖子(使用.Contains方法)。

if (myCache != null && myCache.Contains("keyName") && myCache.Get("keyName") != null)
{
    myDS = (DataSet)myCache.Get("keyName");
}