
mikecat
迈克老猫
-
个人空间
- 组别:管理员
- 性别:
- 来自:中国-石家庄
- 积分:2328
- 帖子:1996
- 注册:
2007-12-31
|
学习PetShop3.0(3)模仿购物车的简单可变类
今天晚上看了近两个小时的购物车,基本把原理弄明白了,先写一个类似结构的类来简单的演示一下 Store类模仿购物车内的物品 public class Store { private string name; private int id; private DateTime time;public Store(string name,int id,DateTime time) { this.name=name; this.id=id; this.time=time; }//属性 public string Name { get{return this.name;} }public int Id { get{return this.id;} }public DateTime Time { get{return this.time;} } }StoreList类模仿购物车 public class StoreList : IEnumerable { ArrayList al=new ArrayList(); public StoreList() {} //向车内添加物品 public void Add(Store st) { this.al.Add(st); }//返回全部物品 public ArrayList List { get{return this.al;} } //实现IEnumerable接口 #region IEnumerable 成员public IEnumerator GetEnumerator() { return this.al.GetEnumerator(); }#endregion//添加一个索引器,注意没有判断索引数的合法性 public Store this[int index] { get{return (Store)al[index];} }//物品的数量 public int Count { get{return al.Count;} } }最后的演示页面 public class TestStore : System.Web.UI.Page { protected System.Web.UI.WebControls.Button addStore; protected System.Web.UI.WebControls.Label showMsg;
private void Page_Load(object sender, System.EventArgs e) { show(); }#region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); }
/// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.addStore.Click += new System.EventHandler(this.addStore_Click); this.Load += new System.EventHandler(this.Page_Load);} #endregion//点击添加按钮后的处理事件,向保存在Session中的购物车添加一个商品 private void addStore_Click(object sender, System.EventArgs e) { Store st=new Store("alex",0,DateTime.Now); //检查Session内是否存有购物车,如没有,则添加一个 if(Session["stxx"]==null) { StoreList sl=new StoreList(); Session["stxx"]=sl; } //从Session中得到购物车,然后向里面添加一个商品 StoreList sls=(StoreList)Session["stxx"]; sls.Add(st); //注意这里,最后分析这个 //Session["stxx"]=sls; }//展示购物车内的商品 private void show() { StringBuilder sb=new StringBuilder(); if(Session["stxx"]!=null) { StoreList sls=(StoreList)Session["stxx"]; //利用索引循环取出商品 for(int i=0;i<sls.Count;i++) sb.Append(sls.Time.ToString()+"<br>"); showMsg.Text=sb.ToString(); } } } Store是一个瘦实体类,而StoreList是一个可变类。StoreList类通过里面的ArrayList保存Store类,并提供了相应的方法来对Store进行操作。 来看这个: //从Session中得到购物车,然后向里面添加一个商品 StoreList sls=(StoreList)Session["stxx"]; sls.Add(st); //注意这里,最后分析这个 //Session["stxx"]=sls; 这里涉及到一个关于Session的问题,由于我们的StoreList保存在了Session中,所以每次操作都要先从Session里把StoreList取出来,但是在操作完后,并没有再把StoreList保存回Session,这主要是因为我们提取出来的并不是Session里保存的值,而只是得到了对Session里保存的值的引用,所以之后的操作其实都是在对Session里保存的值进行,就没有必要最后再保存了。
原文出处:http://blog.csdn.net/sukey00/
|