您的位置:首页 > 运维架构

PetShop3.x学习笔记9-购物车参考资料1-模仿购物车

2006-02-28 08:57 417 查看
今天晚上看了近两个小时的购物车,基本把原理弄明白了,先写一个类似结构的类来简单的演示一下

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

}

}

 

注意:下边演示“返回很多同类型的对象”的方法——使用ArrayList

StoreList类模仿购物车

public class StoreList : IEnumerable

{

ArrayList al=new ArrayList();

public StoreList()

{}

//向车内添加物品

public void Add(Store st)

{

this.al.Add(st);  //添加到ArrayList中的只是此Store实例的引用

}

//返回全部物品

public ArrayList List

{

get{return this.al;}

}

//实现IEnumerable接口

#region IEnumerable 成员

public IEnumerator GetEnumerator()

{

return this.al.GetEnumerator();

}

#endregion

 

//添加一个索引器,注意没有判断索引数的合法性

//这样的方法定义,在使用的时候就可以直接使用“实例[i]进行访问了!!!

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

}

 

//点击添加按钮后的处理事件,向保存在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中!

Session["stxx"]=sl;

}

//从Session中得到购物车,然后向里面添加一个商品

StoreList sls=(StoreList)Session["stxx"];

sls.Add(st);

//在操作完后,并没有再把StoreList保存回Session,这主要是因为我们提取出来的并不是Session里保存的值,而只是得到了对Session里保存的值的引用,所以之后的操作其实都是在对Session里保存的值进行,就没有必要最后再保存了!!!

//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[i].Time.ToString()+"<br>");

showMsg.Text=sb.ToString();

}

}

}




Store是一个瘦实体类,而StoreList是一个可变类。StoreList类通过里面的ArrayList保存Store类,并提供了相应的方法来对Store进行操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息