亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#實(shí)現(xiàn)對(duì)象的序列化和反序列化

 更新時(shí)間:2022年07月31日 15:42:39   作者:Darren?Ji  
這篇文章介紹了C#實(shí)現(xiàn)對(duì)象序列化和反序列化的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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

將對(duì)象及其狀態(tài)保存起來(lái),通常是保存到文件中,叫序列化。
將文件還原為對(duì)象,叫反序列化。

序列化和反序列化的接口和幫助類:

  • 接口IFormatter
    • object Deserialize(Stream serializactionStream)
    • void Serialize(Stream serializationStream, object graph)
  • System.Runtime.Serialization.Formatters.Binary下的BinaryFormatter,將對(duì)象序列化成二進(jìn)制
  • System.Runtime.Serialization.Formatters.Soap下的SoapFormatter,將對(duì)象序列化成人類可讀的文本

什么是SOAP:

Simple Object Access Protocol,簡(jiǎn)單對(duì)象訪問協(xié)議,基于XML協(xié)議。

使用BinaryFormatter序列化對(duì)象保存到文件

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");
        }
    }

注意:

  • 對(duì)象序列化需要打上[Serializable]
  • 不可序列化的字段需要打上[NonSerialized],該屬性只能打在字段上

結(jié)果:

使用BinaryFormatter將文件反序列化成對(duì)象

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

結(jié)果:

注意:

  • 私有字段是可以反序列化的,因?yàn)榉葱蛄谢牡讓邮峭ㄟ^反射來(lái)實(shí)現(xiàn)的,而反射是可以訪問到私有字段的。
  • conn變成了null,這是因?yàn)榉葱蛄谢⒉粫?huì)調(diào)用構(gòu)造函數(shù),而且conn本身設(shè)置成了不可以序列化。

IDeserializationCallback用來(lái)在反序列化后執(zhí)行回調(diào)函數(shù),實(shí)現(xiàn)沒有反序列化字段的實(shí)例化:

   [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");
        }
    }

再次運(yùn)行,得到:

使用SoapFormatter序列化對(duì)象保存到文件

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();

結(jié)果:

使用SoapFormatter:

  • 好處:SOAP是開放的協(xié)議,可以跨平臺(tái)的其他程序也可以使用SoapFormatter序列化的文件
  • 缺點(diǎn):xml文件尺寸比較大

使用序列化和反序列化事件對(duì)對(duì)象進(jìn)行簡(jiǎn)單的加密和解密

主程序:

//序列化
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("序列化前:對(duì)私有字段connString進(jìn)行簡(jiǎn)單加密");
            this.connString = this.connString.Replace("a", "*");
        }
 
        [OnSerialized]
        void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("序列化后:對(duì)私有字段connString進(jìn)行簡(jiǎn)單解密");
            this.connString = this.connString.Replace("*", "a");
        }
 
        [OnDeserializing]
        void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("反序列化前:do nothing~~");
        }
 
        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("反序列化后:對(duì)私有字段connString進(jìn)行簡(jiǎn)單解密,并重新初始化非序列化字段");
            this.connString = this.connString.Replace("*", "a");
            this.conn = new SqlConnection(connString);
        }
 
        public override string ToString()
        {
            return this.connString;
        }
    }

結(jié)果:

通過實(shí)現(xiàn)ISerializable接口自定義序列化過程

主要借助幫助類SerializationInfo,以鍵值對(duì)形式把需要序列化的字段或?qū)傩员4嬖赟erializationInfo中。另外,還需要一個(gè)反序列化時(shí)用于還原屬性值的構(gòu)造函數(shù)。

    [Serializable]
    public class Product : ISerializable
    {
        private string connString;
 
        [NonSerialized]
        public SqlConnection conn;
 
        public Product(string connString)
        {
            this.connString = connString;
        }
 
        //反序列化時(shí)用于還原屬性值的構(gòu)造函數(shù)
        protected Product(SerializationInfo info, StreamingContext context)
        {
            string encrypted = info.GetString("encrypted");
            this.connString = encrypted.Replace("*", "a");
        }
 
        //對(duì)私有字段簡(jiǎn)單加密以鍵值對(duì)形式保存到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;
        }
    }

結(jié)果:

通過實(shí)現(xiàn)ISerializable接口讓沒有實(shí)現(xiàn)序列化的基類可被序列化

有這樣一個(gè)基類,不可以序列化。

    public class ObjectBase
    {
        public string Name;
    }

創(chuàng)建一個(gè)子類繼承不可以序列化的ObjectBase,并實(shí)現(xiàn)ISerializable接口。

    [Serializable]
    public class Product : ObjectBase,ISerializable
    {
        private string connString;
 
        [NonSerialized]
        public SqlConnection conn;
 
        public Product(string connString)
        {
            this.connString = connString;
        }
 
        //反序列化時(shí)用于還原屬性值的構(gòu)造函數(shù)
        protected Product(SerializationInfo info, StreamingContext context)
        {
            string encrypted = info.GetString("encrypted");
            this.connString = encrypted.Replace("*", "a");
            base.Name = info.GetString("name");
        }
 
        //對(duì)私有字段簡(jiǎn)單加密以鍵值對(duì)形式保存到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 = "我來(lái)自基類"};
            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();

結(jié)果:

總結(jié)

  • 使用BinaryFormatter:以二進(jìn)制形式序列化和反序列化的時(shí)候用到。
  • 使用SoapFormatter:以xml形式,或跨平臺(tái)調(diào)序列化和反序列化的時(shí)候用到。
  • [NonSerialized][OnSerializing][OnSerialized][OnDeserializing]這4個(gè)事件可以對(duì)序列化和反序列化過程進(jìn)行細(xì)粒度控制。
  • ISerializable接口:可以把序列化字段或?qū)傩砸枣I值對(duì)形式保存在SerializationInfo中,甚至讓一個(gè)沒有序列化特性的基類實(shí)現(xiàn)序列化。

到此這篇關(guān)于C#序列化和反序列化對(duì)象的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Unity3D 計(jì)時(shí)器的實(shí)現(xiàn)代碼(三種寫法總結(jié))

    Unity3D 計(jì)時(shí)器的實(shí)現(xiàn)代碼(三種寫法總結(jié))

    這篇文章主要介紹了Unity3D 計(jì)時(shí)器的實(shí)現(xiàn)代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2021-04-04
  • 字符串陣列String[]轉(zhuǎn)換為整型陣列Int[]的實(shí)例

    字符串陣列String[]轉(zhuǎn)換為整型陣列Int[]的實(shí)例

    下面小編就為大家分享一篇字符串陣列String[]轉(zhuǎn)換為整型陣列Int[]的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2017-12-12
  • C#控件Picturebox實(shí)現(xiàn)鼠標(biāo)拖拽功能

    C#控件Picturebox實(shí)現(xiàn)鼠標(biāo)拖拽功能

    這篇文章主要為大家詳細(xì)介紹了C#控件Picturebox實(shí)現(xiàn)鼠標(biāo)拖拽功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • C#實(shí)現(xiàn)DevExpress本地化實(shí)例詳解

    C#實(shí)現(xiàn)DevExpress本地化實(shí)例詳解

    這篇文章主要介紹了C#實(shí)現(xiàn)DevExpress本地化,以實(shí)例形式較為詳細(xì)的分析了DevExpress本地化的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-08-08
  • 淺談C# 9.0 新特性之只讀屬性和記錄

    淺談C# 9.0 新特性之只讀屬性和記錄

    這篇文章主要介紹了C# 9.0 新特性之只讀屬性和記錄的的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下
    2020-06-06
  • C#使用CefSharp實(shí)現(xiàn)內(nèi)嵌網(wǎng)頁(yè)詳解

    C#使用CefSharp實(shí)現(xiàn)內(nèi)嵌網(wǎng)頁(yè)詳解

    這篇文章主要介紹了C# WPF里怎么使用CefSharp嵌入一個(gè)網(wǎng)頁(yè),并給出一個(gè)簡(jiǎn)單示例演示C#和網(wǎng)頁(yè)(JS)的交互實(shí)現(xiàn),感興趣的小伙伴可以了解一下
    2023-04-04
  • C#中給Excel添加水印的具體方法

    C#中給Excel添加水印的具體方法

    這篇文章主要介紹了C#中如何給Excel添加水印,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • C#中timer類的用法總結(jié)

    C#中timer類的用法總結(jié)

    System.Windows.Forms.Timer是應(yīng)用于WinForm中的,它是通過Windows消息機(jī)制實(shí)現(xiàn)的,類似于VB或Delphi中的Timer控件,內(nèi)部使用API SetTimer實(shí)現(xiàn)的。它的主要缺點(diǎn)是計(jì)時(shí)不精確,而且必須有消息循環(huán)
    2013-10-10
  • 分享WCF聊天程序--WCFChat實(shí)現(xiàn)代碼

    分享WCF聊天程序--WCFChat實(shí)現(xiàn)代碼

    無(wú)意中在一個(gè)國(guó)外的站點(diǎn)下到了一個(gè)利用WCF實(shí)現(xiàn)聊天的程序,作者是:Nikola Paljetak。研究了一下,自己做了測(cè)試和部分修改,感覺還不錯(cuò),分享給大家
    2015-11-11
  • WPF利用ScottPlot實(shí)現(xiàn)動(dòng)態(tài)繪制圖像

    WPF利用ScottPlot實(shí)現(xiàn)動(dòng)態(tài)繪制圖像

    ScottPlot是基于.Net的一款開源免費(fèi)的交互式可視化庫(kù),支持Winform和WPF等UI框架,本文主要為大家詳細(xì)介紹了如何WPF如何使用ScottPlot實(shí)現(xiàn)動(dòng)態(tài)繪制圖像,需要的可以參考下
    2023-12-12

最新評(píng)論