C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#序列化和反序列化对象

C#实现对象的序列化和反序列化

作者:Darren Ji

这篇文章介绍了C#实现对象序列化和反序列化的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

什么是序列化和反序列化:

将对象及其状态保存起来,通常是保存到文件中,叫序列化。
将文件还原为对象,叫反序列化。

序列化和反序列化的接口和帮助类:

什么是SOAP:

Simple Object Access Protocol,简单对象访问协议,基于XML协议。

使用BinaryFormatter序列化对象保存到文件

using System;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
    class Program
    {
        static void Main(string[] args)
        {
            IFormatter formatter = new BinaryFormatter();
            Product product = new Product(1){Price = 88.5f,Name = "Wind 850"};
            Stream fs = File.OpenWrite(@"F:\product.obj");
            formatter.Serialize(fs, product);
            fs.Dispose();
            Console.WriteLine(product);
            Console.ReadKey();
        }
    }
 
    [Serializable]
    public class Product
    {
        private int id;
 
        [NonSerialized]
        private SqlConnection conn;
 
        public Product(int id)
        {
            this.id = id;
            this.conn = new SqlConnection(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=1");
        }
 
        public string Name { get; set; }
        public double Price { get; set; }
 
        public override string ToString()
        {
            return String.Format("Id:{0},Name:{1},Price:{2},conn:{3}", this.id, this.Name, this.Price,this.conn==null?"Null":"Object");
        }
    }

注意:

结果:

使用BinaryFormatter将文件反序列化成对象

IFormatter formatter = new BinaryFormatter();
Stream fs = File.OpenRead(@"F:\product.obj");
Product product = (Product) formatter.Deserialize(fs);
Console.WriteLine(product);
Console.ReadKey();

结果:

注意:

IDeserializationCallback用来在反序列化后执行回调函数,实现没有反序列化字段的实例化:

   [Serializable]
    public class Product:IDeserializationCallback
    {
        private int id;
 
        [NonSerialized]
        private SqlConnection conn;
 
        public Product(int id)
        {
            this.id = id;
            this.conn = new SqlConnection(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=1");
        }
 
        public string Name { get; set; }
        public double Price { get; set; }
 
        public override string ToString()
        {
            return String.Format("Id:{0},Name:{1},Price:{2},conn:{3}", this.id, this.Name, this.Price,this.conn==null?"Null":"Object");
        }
 
        public void OnDeserialization(object sender)
        {
            this.conn = new SqlConnection(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=1");
        }
    }

再次运行,得到:

使用SoapFormatter序列化对象保存到文件

IFormatter formatter = new SoapFormatter();
Product item = new Product(2){Name = "Hello world",Price = 9.5F};
Stream fs = File.OpenWrite(@"F:\product.soap");
formatter.Serialize(fs, item);
fs.Dispose();

结果:

使用SoapFormatter:

使用序列化和反序列化事件对对象进行简单的加密和解密

主程序:

//序列化
IFormatter formatter = new BinaryFormatter();
Product product = new Product(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=1");
Stream fs = File.OpenWrite(@"F:\product.obj");
formatter.Serialize(fs, product);
fs.Dispose(); 

//反序列化
Stream fs1 = File.OpenRead(@"F:\product.obj");
Product product1 = (Product)formatter.Deserialize(fs1);

Console.WriteLine(product1);
Console.ReadKey();

可序列化类:

    [Serializable]
    public class Product
    {
        private string connString;
        [NonSerialized]
        public SqlConnection conn;
 
        public Product(string connString)
        {
            this.connString = connString;
        }
 
        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {
            Console.WriteLine("序列化前:对私有字段connString进行简单加密");
            this.connString = this.connString.Replace("a", "*");
        }
 
        [OnSerialized]
        void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("序列化后:对私有字段connString进行简单解密");
            this.connString = this.connString.Replace("*", "a");
        }
 
        [OnDeserializing]
        void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("反序列化前:do nothing~~");
        }
 
        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("反序列化后:对私有字段connString进行简单解密,并重新初始化非序列化字段");
            this.connString = this.connString.Replace("*", "a");
            this.conn = new SqlConnection(connString);
        }
 
        public override string ToString()
        {
            return this.connString;
        }
    }

结果:

通过实现ISerializable接口自定义序列化过程

主要借助帮助类SerializationInfo,以键值对形式把需要序列化的字段或属性保存在SerializationInfo中。另外,还需要一个反序列化时用于还原属性值的构造函数。

    [Serializable]
    public class Product : ISerializable
    {
        private string connString;
 
        [NonSerialized]
        public SqlConnection conn;
 
        public Product(string connString)
        {
            this.connString = connString;
        }
 
        //反序列化时用于还原属性值的构造函数
        protected Product(SerializationInfo info, StreamingContext context)
        {
            string encrypted = info.GetString("encrypted");
            this.connString = encrypted.Replace("*", "a");
        }
 
        //对私有字段简单加密以键值对形式保存到SerializationInfo
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            string encrypted = this.connString.Replace("a", "*");
            info.AddValue("encrypted",encrypted);
        }
 
        public override string ToString()
        {
            return this.connString;
        }
    }

结果:

通过实现ISerializable接口让没有实现序列化的基类可被序列化

有这样一个基类,不可以序列化。

    public class ObjectBase
    {
        public string Name;
    }

创建一个子类继承不可以序列化的ObjectBase,并实现ISerializable接口。

    [Serializable]
    public class Product : ObjectBase,ISerializable
    {
        private string connString;
 
        [NonSerialized]
        public SqlConnection conn;
 
        public Product(string connString)
        {
            this.connString = connString;
        }
 
        //反序列化时用于还原属性值的构造函数
        protected Product(SerializationInfo info, StreamingContext context)
        {
            string encrypted = info.GetString("encrypted");
            this.connString = encrypted.Replace("*", "a");
            base.Name = info.GetString("name");
        }
 
        //对私有字段简单加密以键值对形式保存到SerializationInfo
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            string encrypted = this.connString.Replace("a", "*");
            info.AddValue("encrypted",encrypted);
            info.AddValue("name",base.Name);
        }
 
        public override string ToString()
        {
            return String.Format("Name:{0},Conn:{1}", base.Name, this.connString);
        }
    }

主程序:

            //序列化
            IFormatter formatter = new BinaryFormatter();
            Product product = new Product(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=1"){Name = "我来自基类"};
            Stream fs = File.OpenWrite(@"F:\product.obj");
            formatter.Serialize(fs, product);
            fs.Dispose(); 
 
            //反序列化
            Stream fs1 = File.OpenRead(@"F:\product.obj");
            Product product1 = (Product)formatter.Deserialize(fs1);
 
            Console.WriteLine(product1);
            Console.ReadKey();

结果:

总结

到此这篇关于C#序列化和反序列化对象的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文