加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

循环遍历ASP.NET缓存对象中的键

发布时间:2020-12-16 04:07:43 所属栏目:asp.Net 来源:网络整理
导读:ASP.NET中的缓存看起来像使用某种关联数组: // Insert some data into the cache:Cache.Insert("TestCache",someValue);// Retrieve the data like normal:someValue = Cache.Get("TestCache");// But,can be done associatively ...someValue = Cache["Tes
ASP.NET中的缓存看起来像使用某种关联数组:
// Insert some data into the cache:
Cache.Insert("TestCache",someValue);
// Retrieve the data like normal:
someValue = Cache.Get("TestCache");

// But,can be done associatively ...
someValue = Cache["TestCache"];

// Also,null checks can be performed to see if cache exists yet:
if(Cache["TestCache"] == null) {
    Cache.Insert(PerformComplicatedFunctionThatNeedsCaching());
}
someValue = Cache["TestCache"];

如您所见,对缓存对象执行空检查非常有用.

但是我想实现一个可以清除缓存值的缓存清除功能
我不知道整个关键名称.因为似乎有联想
数组在这里,它应该是可能的(?)

任何人都可以帮我找出一种循环存储缓存键的方法
对它们执行简单的逻辑?这就是我所追求的:

static void DeleteMatchingCacheKey(string keyName) {
    // This foreach implementation doesn't work by the way ...
    foreach(Cache as c) {
        if(c.Key.Contains(keyName)) {
            Cache.Remove(c);
        }
    }
}

解决方法

从任何集合类型中删除项目时不要使用foreach循环 – foreach循环依赖于使用枚举器,该枚举器不允许您从集合中删除项目(如果迭代的集合具有项目,则枚举器将抛出异常添加或删除它).

使用简单的while循环缓存键:

int i = 0;
while (i < Cache.Keys.Length){
   if (Cache.Keys(i).Contains(keyName){
      Cache.Remove(Cache.Keys(i))
   } 
   else{
      i ++;
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读