Source code location: ./collections/collectiontest.aspx.cs
using System.Web.UI; using System.Collections.Generic; using System; using System.Web; using System.Collections.ObjectModel; using System.Web.Caching; public partial class CollectionTest : Page { // ----------------------------------------------------------------- class Book { string title = null; double price = 0.0; private Book () { } public Book (string title, double price) { this.title = title; this.price = price; } public string Title { get { return this.title; } } public double Price { get { return this.price; } } } // ----------------------------------------------------------------- class BookCollection : Collection<Book> { } // ----------------------------------------------------------------- protected override void OnLoad (EventArgs e) { base.OnLoad(e); BookCollection books = null; int itemCount = 0; books = GetBooksInternal (); /* The count is 3 */ itemCount = books.Count; books.RemoveAt (1); /* What happened here is you modified the collection in * the cache because you were manipulating a reference to it, * not a "disconnected" snapshot. */ books = GetBooksInternal (); /* The count is 2, not 3. */ itemCount = books.Count; } // ----------------------------------------------------------------- private BookCollection GetBooksInternal () { Cache cache = HttpContext.Current.Cache; BookCollection books = cache ["Titles"] as BookCollection; if (books == null) { books = new BookCollection (); books.Add (new Book ("Refactoring Databases", 34.95)); books.Add (new Book ("Refactoring to Patterns", 38.25)); books.Add (new Book ("Refactoring: Improving the Design of Existing Code", 41.95)); cache.Insert ("Titles", books); } return books; } }
Copyright © 2004-2006, Milan Negovan. All rights reserved. | License
Back to AspNetResources.com