阅读HttpRuntime.Cache项目为只读 [英] Read HttpRuntime.Cache item as read-only
问题描述
我使用的是 HttpRuntime.Cache
来存储将经常在会话被访问对象的列表。
I am using a HttpRuntime.Cache
to store a list of objects that will be accessing frequently across sessions.
我用code以下行从缓存中获得该项目:
I use the following line of code to get the item from the cache:
List<chartData_Type> _chartData =
(List<chartData_Type>)HttpRuntime.Cache.Get("rollingMonth");
但不幸的是,当我更新的 _chartData STRONG>,它更新缓存的项目了。
But, unfortunately when I update the _chartData, it updates the cached item too.
如何能简单地得到缓存项目的副本?
How can I simply get a copy of the cached item?
推荐答案
这是.NET的作品,因为缓存只是参照列表$的指针的方式C $ C>。不知道你
chartData_Type
是否是值类型或引用类型。
That is the way which .NET works because Cache just reference to the pointer of List
. Don't know whether you chartData_Type
is value type or reference type.
如果值类型,它很容易使用
If value type, it is easy to use:
List<chartData_Type> list = new List<chartData_Type>(_chartData);
但是,如果引用类型,它涉及到复杂的,需要实现的 <一个href="http://www.$c$cproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects#xx3984032xx">DeepCopy方法类,然后执行的DeepCopy
在列表中的每个对象。
But if reference type, it comes to complicated, you need to implement DeepCopy method for your class, then do DeepCopy
for each object in list.
DeepClone
方法:
public static class CloneHelper
{
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
}
为了使用这个方法,类 chartData_Type
必须注明 [Serializable接口]
:
In order to use this method, class chartData_Type
must be marked [Serializable]
:
[Serializable]
class chartData_Type
{}
所以,你可以手工做深克隆:
So, you can do deep clone manually:
var cloneChartData = _chartData.Select(d =>
CloneHelper.DeepClone<chartData_Type>(d))
.ToList();
这篇关于阅读HttpRuntime.Cache项目为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!