C#序列化/反序列化

C#序列化/反序列化

序列化:将实体类以二进制或者XML的形式保存到磁盘或者内存中。

反序列化:将序列化的二进制文件和XML文件解析成实体类。

例如下面的二进制序列化与反系列化:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;

protected void Page_Load(object sender, EventArgs e)
        {
            fun_Serializable();//序列化
            fun_oppositeSerializable();//反序列化
        }

[Serializable]//表示该类可以被序列化
        public class person {
            public string name;
            public string sex;
            public person(string name,string sex){
                this.name = name;
                this.sex = sex;
            }
        }

//序列化与反序列化 必须是同一存在的对象。公共的 序列化与反序列化都用此对象
        public static string fileName = @"H:person1.dat";//序列化成二进制数据保存到程序本地
        public Stream fstream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
        public BinaryFormatter binformat = new BinaryFormatter();


/// <summary>
        /// 序列化
        /// 使用二进制序列化,必须为每一个要序列化的的类和其关联的类加上[Serializable]特性,
        /// 对类中不需要序列化的成员可以使用[NonSerialized]特性。
        /// </summary>
        public void fun_Serializable() {
            List<person> ls = new List<person>();
            ls.Add(new person("php1", "nan"));
            ls.Add(new person("php2", "nv"));
            binformat.Serialize(fstream, ls);
            //xmlFormat.Serialize(fstream, ls);
            ls.Clear();
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        public void fun_oppositeSerializable()
        {
            fstream.Position = 0;
            List<person> ls =(List<person>)binformat.Deserialize(fstream);
            foreach (person p in ls)
            {
                //Console.WriteLine(p.name +":"+p.sex);//是输出到屏幕的,一般用在控制台程序中,而且输出的是一行。下一个输出在下一行显示。
                Response.Write(p.name + ":" + p.sex);  //是输出到网页的,一般用在WebSite或者WebApplaction中,输出的不是一行。下一个输出接续上一个输出的末尾。
            }
        }