.NET 7 MemoryCache GetProperty returns null



我有一段代码可以在。net 6中正常工作,但是自从我升级到。net 7后,代码就不能工作了。

下面是代码;

// Get the empty definition for the EntriesCollection
var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (cacheEntriesCollectionDefinition!=null)
{

// Populate the definition with your IMemoryCache instance.  
// It needs to be cast as a dynamic, otherwise you can't
// loop through it due to it being a collection of objects.
var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_cache) as dynamic;
if (cacheEntriesCollection!=null)
{
// Define a new list we'll be adding the cache entries too
List<ICacheEntry> cacheCollectionValues = new List<ICacheEntry>();
foreach (var cacheItem in cacheEntriesCollection)
{
// Get the "Value" from the key/value pair which contains the cache entry   
ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
// Add the cache entry to the list
cacheCollectionValues.Add(cacheItemValue);
}

var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList();
foreach (var key in keysToRemove)
{
_cache.Remove(key);
}
}
}

typeof (MemoryCache) . getproperty("EntriesCollection"总是返回null。我该如何解决这个问题?

MemoryCache内部设计发生变化。源代码见GitHub。

如果你在非公共成员上有一个绑定,那么你必须随时计算实现更改的选项,即使是在。net做了一个小的更新。

当这些绑定是必须时,最好开发一个单独的单元测试来验证这些代码是否正常工作。

最新更新