.net 7 获取所有缓存键的问题?

这里是群友提供听说是issue提的问题,高手回答的。

var
coherentState = _cache.GetType().GetField("_coherentState", BindingFlags.NonPublic | BindingFlags.Instance); var coherentStateValue = coherentState.GetValue(_cache); var entriesCollection = coherentStateValue.GetType().GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance); var entriesCollectionValue = entriesCollection.GetValue(coherentStateValue) as ICollection; var keys = new List<string>(); if (entriesCollectionValue != null) { foreach (var item in entriesCollectionValue) { var methodInfo = item.GetType().GetProperty("Key"); var val = methodInfo.GetValue(item); keys.Add(val.ToString()); } } return keys;

由于.net 7源码改变了,_entries外面又套了一层_coherentState,致使无法获取所有键值。

通过查看源码我自己修改了如下代码:

       var ggt = _cache.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(_cache));
                            if (eee != null)
                            { 
                                var cacheItems = eee as IDictionary;
                                if (cacheItems == null) return keys;
                                foreach (DictionaryEntry cacheItem in cacheItems)
                                {
                                    if (!string.IsNullOrEmpty(key))
                                    {
                                        if (cacheItem.Key.ToString().Contains(key))
                                        {
                                            keys.Add(cacheItem.Key.ToString());
                                        }
                                    }
                                    else
                                    {
                                        keys.Add(cacheItem.Key.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
         
            return keys;

 

posted @ 2022-11-30 09:02  永恒一生  阅读(110)  评论(0编辑  收藏  举报