我正在尝试在.NET 4.0中使用System.Runtime.Caching.MemoryCache类。我有一个通用方法,所以我可以将任何类型传递到内存缓存中,并在调用时获取它。
该方法返回的是一个object类型的对象,其中包含了一个名为Value的字段,该字段包含了缓存对象。
我的问题是,如何将我收到的对象强制转换为对应的类型?
以下是我的代码...
public static class ObjectCache
{
private static MemoryCache _cache = new MemoryCache("GetAllMakes");
public static object GetItem(string key)
{
return AddOrGetExisting(key, () => InitialiseItem(key));
}
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
{
var newValue = new Lazy<T>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
_cache.Remove(key);
throw;
}
}
/// <summary>
/// How can i access Value and cast to type "List<IBrowseStockVehicle>"
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private static object InitialiseItem(string key)
{
// SearchVehicleData.GetAllMakes(false) is of type List<IBrowseStockVehicle>
return new { Value = SearchVehicleData.GetAllMakes(false) };
}
}
以及单元测试(Unit Test)...
[TestMethod]
public void TestGetAllMakes_Cached()
{
dynamic ReturnObj = ObjectCache.GetItem("GetAllMakes");
// *********************************************
// cannot do this as tester is of type Object and doesnt have teh field Value
foreach(IBrowseStockVehicle item in ReturnObj.Value)
{
}
}