悲催了,升到net7.0 ,缓存不能用了,之前6.0好好的,从未出现未定义的情况! 返回
各位老大,看看有什么补救办法,感觉GetField("_entries", flags) 有问题!

该方法代码如下:
/// <summary>
/// 获取所有缓存键
/// </summary>
/// <returns></returns>
public static List<string> GetCacheKeys()
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var entries = _memoryCache.GetType().GetField("_entries", flags).GetValue(_memoryCache);
var cacheItems = entries as IDictionary;
var keys = new List<string>();
if (cacheItems == null) return keys;
foreach (DictionaryEntry cacheItem in cacheItems)
{
keys.Add(cacheItem.Key.ToString());
}
return keys;
}
热忱回答(8)
-
goodgame36 VIP0
2023/1/23网上找到答案了,发出来,可能大家碰到时有用,按作者的说法 由于.net 7源码改变了,_entries外面又套了一层_coherentState,致使无法获取所有键值。
public static List<string> GetCacheKeys() { var ggt = _memoryCache.GetType(); var _coherentStates = ggt.GetRuntimeFields(); var keys = new List<string>(); foreach (var f in _coherentStates) { if (f.Name == "_coherentState") { var ftype = f.FieldType; var ssss = ftype.GetRuntimeFields(); foreach (var ss in ssss) { if (ss.Name == "_entries") { var eee = ss.GetValue(f.GetValue(_memoryCache)); if (eee != null) { var cacheItems = eee as IDictionary; if (cacheItems == null) return keys; foreach (DictionaryEntry cacheItem in cacheItems) { keys.Add(cacheItem.Key.ToString()); } } } } } } return keys; }原出处地址是: https://www.cnblogs.com/duoe/p/16937377.html (里面有几处错语,可能是作者的上下文有提供 就是 key 这个变量未见声明,也不知用途,我直接去掉了)
0 回复 -
fate sta VIP0
2023/1/23你写麻烦了
0 回复 -
fate sta VIP0
2023/1/23//.NET 7//var coherentState = _memoryCache.GetType().GetField("_coherentState", flags).GetValue(_memoryCache);//var entries = coherentState.GetType().GetField("_entries", flags).GetValue(coherentState);0 回复 -
fate sta VIP0
2023/1/23文档也更新过了
0 回复 -
goodgame36 VIP0
2023/1/23@fate sta:太感谢了,原来加多一句就可以了啊,国家队出场果然不同,老大太历害了,再次表示感谢!
0 回复 -
Lucky Stars VIP0
2025/3/3var coherentState = Cache.GetType().GetField("_coherentState", flags).GetValue(Cache);
var entries = coherentState.GetType().GetField("_stringEntries", flags).GetValue(coherentState);
升级后要用这个字段了 _stringEntries
0 回复 -
柠檬苏打 VIP0
2025/6/4我只是安装了.net10的sdk,项目版本一直是.net6,为什么也会报错呢
0 回复 -
fate sta VIP0
2025/6/4@柠檬苏打:反射看一下哪些属性,拿出需要的属性
0 回复