Read HttpRuntime.Cache item as read-only

≯℡__Kan透↙ 提交于 2019-12-01 04:05:18

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);

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 method:

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);
        }
    }
}

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();

Use:

List<chartData_Type> list = new List<chartData_Type>(_chartData);

It will copy all items from _chartData to list.

List is a reference type and _chartData holds the address of the original object stored in the cache. That is why when you update _chartData, it updates the cached object too. If you want a separate object then clone the cached object. See below reference

http://www.codeproject.com/Articles/33364/ASP-NET-Runtime-Cache-Clone-Objects-to-Preserve-Ca

http://www.codeproject.com/Articles/45168/ASP-NET-Runtime-Cache-Clone-Objects-to-Preserve-Ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!