将缓存项转换为特定对象类型,以便通过webmethod返回

时间:2014-10-08 15:07:41

标签: c# .net web-services caching

我已经成功地在Web服务中缓存了一个大型数据项,但是如果我想稍后返回该缓存项而不是再次运行冗长的查询,我如何将通用缓存项转换为我自己设计的对象?

例如

HttpContext.Current.Cache.Insert("cItem", [MyItem]));

然后

return HttpContext.Current.Cache["cItem"];

将在Visual Studio中显示错误,因为我无法转换类型' object'我自己的类型。 任何指针都赞赏 感谢

2 个答案:

答案 0 :(得分:3)

Cache[string] returns an object。虽然MyItem的任何实例都可以隐式转换为object,但反过来显然不正确。

因此,如果您的方法的返回类型为MyItem,那么您需要转换缓存的项目:

public MyItem MyMethod()
{
    return (MyItem)HttpContext.Current.Cache["cItem"];
}

这是从缓存中检索时完成的,而不是在存储时。

如果项目可能不是预期类型的​​,则必须以某种方式处理该条件。如果发生这种情况,上面的代码将抛出InvalidCastException。如果你想在这种情况下返回null,你可以尝试这样做:

public MyItem MyMethod()
{
    return HttpContext.Current.Cache["cItem"] as MyItem;
}

答案 1 :(得分:1)

// if its a string etc.
return (string)HttpContext.Current.Cache["cItem"]; 

// if its a List of a custom object 
return (List<CustomObject>)HttpContext.Current.Cache["cItem"];