2016-08-01 90 views
0

我正在實現帶有派生的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)?

+0

從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

+0

@hdz是的,我認爲我有一個錯誤的假設如何在更大的緩存結構中使用CacheItem。我認爲所有的額外信息都與它一起存儲,但似乎並非如此。 – Xedni

回答

1

的原因是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); 
+0

啊,有趣。我想我有一個錯誤的假設,即CacheItem是我應該重寫的,而不僅僅是價值。謝謝! – Xedni