从 MemoryCache 获取自定义 CacheItems

Getting custom CacheItems from MemoryCache

我正在使用派生的 CacheItem 实现 MemoryCache,但是一旦它在缓存中就很难与之交互。例如:

class Program
{
    static void Main(string[] args)
    {
        MemoryCache cache = MemoryCache.Default;
        CacheItemPolicy policy = new CacheItemPolicy();
        CustomCacheItem someItem = (CustomCacheItem)cache.AddOrGetExisting(new CustomCacheItem(1, "tacos", "waffles"), policy);

        Console.ReadLine();
    }
}

public class CustomCacheItem : CacheItem
{
    public int FailureCt { get; set; }

    public CustomCacheItem(int _failureCt, string _key, string _value)
        : base(_key, _value)
    {
        FailureCt = _failureCt;
    }
}

这会引发一个 Unable to cast object of type 'System.Runtime.Caching.CacheItem' to type 'CacheTest.CustomCacheItem'. 的错误,这在某种程度上是有道理的;也许它不保留有关放入的缓存项的信息。但如果是这样,我如何取出我的自定义缓存项?如果 return 值是通用基类型,我如何与 属性(在本例中为 FailureCt)交互?

原因是 MemoryCache.AddOrGetExisting(CacheItem, CacheItemPolicy) 正在内部创建一个新的 CacheItem:

public override CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
{
    if (item == null)
        throw new ArgumentNullException("item");
    return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy));
}

MemoryCache source code


我建议将 FailureCt 存储在值本身而不是 CacheItem 包装器中:

public class CacheValue
{
    public int FailureCt { get; set; }
    public string Value { get; set; }
}

然后:

CacheValue someItem = (CacheValue)cache.AddOrGetExisting("tacos", new CacheValue()
{
    FailureCt = 1,
    Value = "waffles"
}, policy);