使用Asp.Net Cache功能时遇到问题.我将一个对象添加到Cache然后在另一个时间从Cache中获取该对象,修改其中一个属性然后将更改保存到数据库.
但是,下次我从Cache获取对象时,它包含更改的值.因此,当我修改对象时,它会修改缓存中包含的版本,即使我没有在缓存中专门更新它.有谁知道如何从Cache中获取一个不引用缓存版本的对象?
即
步骤1:
Item item = new Item();
item.Title = "Test";
Cache.Insert("Test", item, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
第2步:
Item item = (Item)Cache.Get("test");
item.Title = "Test 1";
第3步:
Item item = (Item)Cache.Get("test");
if(item.Title == "Test 1"){
    Response.Write("Object has been changed in the Cache.");
}
我意识到,通过上面的例子,对项目的任何更改都会反映在缓存中是有意义的,但我的情况有点复杂,我绝对不希望这种情况发生.
Sky*_*ers 17
缓存就是这样,它会缓存您放入其中的任何内容.
如果您缓存引用类型,请检索引用并对其进行修改,当然,下次检索缓存项时,它将反映修改.
如果您希望拥有不可变的缓存项,请使用结构.
Cache.Insert("class", new MyClass() { Title = "original" }, null, 
    DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
MyClass cachedClass = (MyClass)Cache.Get("class");
cachedClass.Title = "new";
MyClass cachedClass2 = (MyClass)Cache.Get("class");
Debug.Assert(cachedClass2.Title == "new");
Cache.Insert("struct", new MyStruct { Title = "original" }, null, 
    DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
MyStruct cachedStruct = (MyStruct)Cache.Get("struct");
cachedStruct.Title = "new";
MyStruct cachedStruct2 = (MyStruct)Cache.Get("struct");
Debug.Assert(cachedStruct2.Title != "new");
| 归档时间: | 
 | 
| 查看次数: | 6098 次 | 
| 最近记录: |