【发布时间】:2017-01-04 10:54:43
【问题描述】:
我正在尝试使用 .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) };
}
}
还有单元测试...
[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)
{
}
}
【问题讨论】:
-
答案是:不要为此使用匿名类型,使用适当的命名类型。
-
解决办法是声明一个类型。
-
匿名类型可作为
internal访问,这意味着您必须添加一个程序集属性以使用属性InternalsVisibleToAttribute向测试项目公开内部类型。 -
在同一个程序集中,可能有....“hacks”,但跨程序集,不行。使用正确的命名类型。
标签: c# .net generics memorycache