日期:2014-05-18  浏览次数:20379 次

利用对象序列化将购物车保存在Cookie中
最近做一个购物类网站,正好在学习对象序列化,于是突然奇想,想把购物车对象(里面已经封装了很多购物车的常用方法)序列化后,将序列化后的字符串保存在Cookie中,需要时,现从Cookie中取出该字符串,反序列化为购物车对象

主要代码如下:
购物车类ShopCart.cs:
----------------------------------------------------------------
using   System;
using   System.Collections;

///   <summary>
///   购物车类
///   </summary>
[Serializable]
public   class   ShopCart
{
      ...详细内容见附件
     
}

以下是调用页面:
Demo.aspx
---------------------------------------------------
<%@   Page   Language= "C# "   AutoEventWireup= "true "   CodeFile= "Demo.aspx.cs "   Inherits= "Public_Test_Demo "   %>

<!DOCTYPE   html   PUBLIC   "-//W3C//DTD   XHTML   1.0   Transitional//EN "   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<html   xmlns= "http://www.w3.org/1999/xhtml "   >
<head   runat= "server ">
        <title> 无标题页 </title>
</head>
<body>
        <form   id= "form1 "   runat= "server ">
        <div>
                <asp:GridView   ID= "GridView1 "   runat= "server ">
                </asp:GridView>
                <br/>
                <asp:Button   ID= "btnReadCookie "   runat= "server "   Text= "读取Cookie中的ShopCart "   OnClick= "btnReadCookie_Click "   /> &nbsp; </div>
        </form>
</body>
</html>

--------------------------------------------
Code-behind端代码:Demo.aspx.cs
--------------------------------------------
using   System;
using   System.Collections;
using   System.Web;
using   System.Runtime.Serialization;
using   System.Runtime.Serialization.Formatters.Binary;
using   System.IO;
using   System.Text;


public   partial   class   Public_Test_Demo   :   System.Web.UI.Page
{
        string   CookieName   =   "ShopCart ";

        protected   void   Page_Load(object   sender,   EventArgs   e)
        {
               

                if   (!IsPostBack)
                {
                        ShopCart   SC   =   new   ShopCart();
                        SC.AddItem( "1 ",   "ProductName ",   "ProductName ",   0,   0,   "ProductID ",   " ",   0,   0,   0,   0,   "ShopId ",   "TestUrl ",   true);