【发布时间】:2016-08-01 19:57:16
【问题描述】:
我正在使用派生的 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'. 的错误,这是有道理的;也许它不会保留有关放入的缓存项的信息。但是如果是这样,我该如何取出我的自定义缓存项?如果返回值是泛型基类型,我如何与该属性(在本例中为 FailureCt)进行交互?
【问题讨论】:
-
从CacheItem派生的目的是什么? CacheItem 只是作为缓存的入口和数据的包装器。
CacheItem item = (CacheItem)cache.AddOrGetExisting(new CacheItem(1, "tacos", "waffles"), policy);item.value 会给你数据。 请注意,按照文档状态,如果密钥存在,这将返回 null https://msdn.microsoft.com/en-us/library/dd988741.aspx -
@hdz 是的,我认为我对如何在更大的缓存结构中使用 CacheItem 有一个错误的假设。我以为所有额外的信息都与它一起存储,但似乎并非如此。
标签: c# .net memorycache