首页 > 其他分享 >MemoryCache 7.0.0.0 版本下获取所有缓存Key

MemoryCache 7.0.0.0 版本下获取所有缓存Key

时间:2023-03-08 14:12:55浏览次数:37  
标签:coherentStateFiledInfo MemoryCache 0.0 7.0 BindingFlags Key entries var

在使用.Net 7.0的过程种,用到微软的MemoryCache,在封装通用接口的时候需要获取所有CacheKey。

目前搜索到的方案都是直接取“_entries” 私有字段。 但在7.0版本之后被包裹在“_coherentState”中,需要通过GetRuntimeFields来获取。

首先说明_memoryCache变量是MemoryCache类的实例,具体代码如下:

1         const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
2         var coherentStateFiledInfo = _memoryCache.GetType().GetField("_coherentState", flags);
3         var coherentStateValue = coherentStateFiledInfo.GetValue(_memoryCache);
4         var entriesFiledInfo = coherentStateFiledInfo.FieldType.GetRuntimeFields().Where(f => f.Name == "_entries").FirstOrDefault();
5         var entries = entriesFiledInfo.GetValue(coherentStateValue);
6          
7         var cacheItems = entries as IDictionary;

这里 cacheItems 就是所有的key和value了。

标签:coherentStateFiledInfo,MemoryCache,0.0,7.0,BindingFlags,Key,entries,var
From: https://www.cnblogs.com/cnwhm/p/17191807.html

相关文章