转载 C# 序列化与反序列化意义详解

时间:2021-04-20 17:48:56

C# 序列化与反序列化意义详解

总结:

①序列化基本是指把一个对象保存到文件或流中,比如可以把文件序列化以保存到Xml中,或一个磁盘文件中
②序列化以某种存储形式使自定义对象持久化; 
③将对象从一个地方传递到另一个地方。 
④将类的值转化为一个一般的(即连续的)字节流,然后就可以将该流写到磁盘文件或任何其他流化目标上。 
⑥序列是指将对象的实例状态存储到存储媒体的过程。 
在此过程中,先将对象的公共字段以及类的名称(包括类的程序集)转换为字节流,然后再把字节流写入数据流。在随后对对象进行反序列化时,将创建出与原对象完全相同的副本。
⑦用处非常大,用于数据传输,对象存贮等。

这些是我通过网上多方参考再结合自己的经验总结的。还是看实例。

【实例1】:

using System;

using System.IO; //文件操作相关
using System.Runtime.Serialization.Formatters.Binary; //包含 BinaryFormatter 类,该类可用于以二进制格式将对象序列化和反序列化。

namespace SerializeDeserialize
{
    class Program
    {
        static void Main(string[] args)
        {
            Program P = new Program();
            P.SerializeStudent();
            P.DeSerializeStudent();
        }
        public void SerializeStudent()
        {
            Student c = new Student();
            c.Id = 0;
            c.Name = "小江";
            c.Sex = "女";
            c.Qq = "676596050";
            c.Homepage = "http://hi.baidu.com/jiang_yy_jiang";
            //创建二进制文件temp.dat
            FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Create);
            BinaryFormatter b = new BinaryFormatter();

//将Student实例对象序列化给fileStream流:其含义是这时候的Student对象已经存储到temp.dat 文件中
            b.Serialize(fileStream, c);
            fileStream.Flush();
            fileStream.Close();
            fileStream.Dispose();
        }
        public void DeSerializeStudent()
        {

Student c = new Student();
            //下面三个属性输出时没有更改,因为反序列化实例化了一个新的Student
            c.Id = 1;
            c.Qq = "676596051";
            c.Homepage = "http://www.baidu.com/jiang_yy_jiang";
            FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryFormatter b = new BinaryFormatter();
            //将temp.dat 的文件流反序列化为Student
            c = b.Deserialize(fileStream) as Student;
            c.Name = "江正";
            c.Sex = "男";
            Console.Write("编号:" + c.Id + "\n姓名:" + c.Name + "\n性别:" + c.Sex + "\nQQ:" + c.Qq + "\n主页:" + c.Homepage);
            Console.ReadLine();
            //释放文件流资源
            fileStream.Flush();
            fileStream.Close();
            fileStream.Dispose();
        }

/// <summary>
        /// 创建6个可读可写的属性
        /// </summary>
        [Serializable]
        public class Student
        {
            //编号
            private int id;
            //姓名
            private string name;
            //性别
            private string sex;
            //QQ
            private string qq;
            //主页
            private string homepage;

public int Id
            {
                get { return id; }
                set { id = value; }
            }
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            public string Sex
            {
                get { return sex; }
                set { sex = value; }
            }
            public string Qq
            {
                get { return qq; }
                set { qq = value; }
            }
            public string Homepage
            {
                get { return homepage; }
                set { homepage = value; }
            }

}

}
}

上面的序列化会将Student类实例存储到temp.dat 文件中,相反的反序列化就会实现将temp.dat中的数据反向生成Student对象

方便理解,其中在本实例中C:\temp.dat内容是:

KSerializeDeserialize, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null    $SerializeDeserialize.Program+Student    id name sex qq           灏忔睙    濂?    676596050

可以看出已经转换为了二进制编码。

效果是:

转载  C# 序列化与反序列化意义详解

【实例2】:

using System;

using System.Collections; //HashTable 所在的命名空间
using System.IO;           //FileStream所在的命名空间
using System.Runtime.Serialization.Formatters.Binary; //序列化反序列化进制转换空间

namespace Same1
{
    class Program
    {
        static void Main(string[] args)
        {
            Serialize();
            Deserialize();
            Console.ReadLine();
        }
        static void Serialize()
        {
            //创建一个包含值的HashTable最后将被序列化
            Hashtable addresses = new Hashtable();
            addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
            addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
            addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
            //为了将HashTable序列化,需要创建一个File Stream
            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
            // 利用二进制格式化将 Hashtable序列化至文件流中
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, addresses);
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
                Console.WriteLine("序列化失败原因是: " + e.Message);
                throw;
            }
            finally
            {
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
        }
        static void Deserialize()
        {
            // 声明一个HashTable
            Hashtable addresses = null;
            // 打开你需要反序列化的文件,并以流的形式输出
            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                //反序列化文件流为HashTable
                addresses = (Hashtable)formatter.Deserialize(fs);
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
                Console.WriteLine("反序列化失败,原因是: " + e.Message);
                throw;
            }
            finally
            {
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            //为了验证反序列化是否成功,将HashTale中的键、值对输出
            foreach (DictionaryEntry de in addresses)
            {
                Console.WriteLine("{0} 的出生地是: {1}.", de.Key, de.Value);
            }
        }
    }
}

DateFile.dat 内容是:

System.Collections.Hashtable    
LoadFactor Version Comparer HashCodeProvider HashSize Keys Values System.Collections.IComparer$System.Collections.IHashCodeProvider 霶8?

Mary    Jeff    Fred          "PO Box 112233, Palo Alto, CA 94301    "123 Main Street, Redmond, WA 98052     987 Pine Road, Phila., PA 19116

效果如下:

转载  C# 序列化与反序列化意义详解