我正在實現帶有派生的CacheItem的MemoryCache,但一旦它進入緩存後就很難與其交互。例如:從MemoryCache中獲取自定義的CacheItems
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](https://msdn.microsoft.com /en-us/library/dd988741.aspx) – hdz
@hdz是的,我認爲我有一個錯誤的假設如何在更大的緩存結構中使用CacheItem。我認爲所有的額外信息都與它一起存儲,但似乎並非如此。 – Xedni