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

前端之家收集整理的这篇文章主要介绍了循环遍历ASP.NET缓存对象中的键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ASP.NET中的缓存看起来像使用某种关联数组:
  1. // Insert some data into the cache:
  2. Cache.Insert("TestCache",someValue);
  3. // Retrieve the data like normal:
  4. someValue = Cache.Get("TestCache");
  5.  
  6. // But,can be done associatively ...
  7. someValue = Cache["TestCache"];
  8.  
  9. // Also,null checks can be performed to see if cache exists yet:
  10. if(Cache["TestCache"] == null) {
  11. Cache.Insert(PerformComplicatedFunctionThatNeedsCaching());
  12. }
  13. someValue = Cache["TestCache"];
@H_403_4@如您所见,对缓存对象执行空检查非常有用.

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

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

  1. static void DeleteMatchingCacheKey(string keyName) {
  2. // This foreach implementation doesn't work by the way ...
  3. foreach(Cache as c) {
  4. if(c.Key.Contains(keyName)) {
  5. Cache.Remove(c);
  6. }
  7. }
  8. }

解决方法

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

  1. int i = 0;
  2. while (i < Cache.Keys.Length){
  3. if (Cache.Keys(i).Contains(keyName){
  4. Cache.Remove(Cache.Keys(i))
  5. }
  6. else{
  7. i ++;
  8. }
  9. }

猜你在找的asp.Net相关文章