思路:
一、将对象序列化为字符串
二、将序列化后的对象保存到Cookies/Session中
三、读取保存在Cookies/Session中的字符串
四、反序列化,将其还原为对象
实现:
(1)一个对象要序列,必须在类定义的时候,加上[Serializable]特性
(2)为了避免处理中文时的异常,先将其编码为Base64,再存储到Cookies/Session中
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
namespace Com.LoRui
{
public class LoRuiTester
{
public static void Main()
{
//用于测试的一个User实例。注意,这里用了C# 3.0的新语法
User user = new User
{
UserName = “LoRui”,
Password = “1234567″,
RealName = “龙睿”,
LoginTimes = 32
};
//序列化
string user2str = Serializer.SerializeObject(user);
Console.WriteLine(user2str);
////保存到Cookies
//HttpContext.Current.Response.Cookies[COOKIES_NAME].Value = user2str;
//反序列化
string str = user2str;
////从Cookies读取
//str = HttpContext.Current.Request.Cookies[COOKIES_NAME].Value;
User str2user = Serializer.DeserializeObject(str);
Console.WriteLine(”UserName: {0}, Password: {1}, RealName: {2}, LoginTimes: {3}”,
str2user.UserName,
str2user.Password,
str2user.RealName,
str2user.LoginTimes);
Console.ReadKey();
}
}