C# 序列化簡單學習

一、 什么是序列化对象?
     序列化是将对象状态转换为可保持或传输的格式的过程。     
     在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,就使得数据能够被轻松地存储和传输。
        确切的说应该是对象的序列化,一般程序在运行时,产生对象,这些对象随着程序的停止运行而消失,但如果我们想把某些对象(因为是对象,所以有各自不同的特性)保存下来,在程序终止运行后,这些对象仍然存在,可以在程序再次运行时读取这些对象的值,或者在其他程序中利用这些保存下来的对象。这种情况下就要用到对象的序列化。
        

      System.Runtime.Serialization和System.Runtime.Serialization.Formatters命名空間中提供了序列化對象的基礎架構。這兩個類實現了基礎架構。

二、 Framework中有两个可用的实现方式:
       System.Runtime.Serialization.Formatters.Binary:這個命名空間也包含了BinaryFormatter類,它能把對象序列化為二進制數據,把二進制數據序列化為對象。
       System.Runtime.Serialization.Formatters.Soap:這個命名空間包含了SoapFormatter類中,它能把對象序列化為SOAP格式的XML數據,把SOAP格式的XML數據序列為對象。

三、例子:
 1、新增一個Windows應用程序,其中Form1有兩個TextBox控件
      注:txb:用於顯示傳入值後,Product類產生的結果
            txbResult:用於顯示反序列化後的結果
 2、增加一個Product類,主要作用是對傳入值格式化
 3、在應用程序中對Product類產生的結果進行序列化

代碼:
  Product類的代碼:
namespace SerializerFile
{
    
/// <summary>
    
/// 此類用作對值入值格式化
    
/// Serializable:作此標記後方可序列化
    
/// </summary>
    [Serializable]
    
class Product
    {
        
public long lId;
        
public string sName;
        
public double dPrice;

        
/// <summary>
        
/// 加上此標記無法序列化
        
/// </summary>
        [NonSerialized]
        
string sNotes;

        
public Product(long alId, string asName, double adPrice, string asNotes)
        {
            lId 
= alId;
            sName 
= asName;
            dPrice 
= adPrice;
            sNotes 
= asNotes;
        }
        
        
public override string ToString()
        {
            
//格式化傳入的值
            return string.Format("{0}:{1} (${2:F2}) {3}", lId, sName, dPrice, sNotes);
        }
    }
}

  Form1中的代碼:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace SerializerFile
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
            
//調用序列化方法
            SerializationClass();
        }

        
/// <summary>
        
/// 序列化方法
        
/// </summary>
        private void SerializationClass()
        {
            List
<Product> products = new List<Product>();
            
//生成值
            products.Add(new Product(1"Spiky Pung"1000.00"Good stuff."));
            products.Add(
new Product(2"Gloop Galloop Soup"25.0"Tasty."));
            products.Add(
new Product(4"Hat Sauce"12.0"One for the kids."));

            
//為了方便,在界面中顯示生成的值
            foreach (Product pProduct in products)
            {
                txb.Text 
+= pProduct.ToString()+"\b\r";
            }

            
//定義可序列化接口
            IFormatter ifSerializer = new BinaryFormatter();

            FileStream fsSaveFile 
= new FileStream(@"D:\Products.bin",FileMode.Create,FileAccess.Write);
            
//序列化(將products中的內容序化到文件D:\Products.bin)
            ifSerializer.Serialize(fsSaveFile,products);
            fsSaveFile.Close();

            FileStream fdLoadFile 
= new FileStream(@"D:\Products.bin", FileMode.Open, FileAccess.Read);
            
//反序列化
            List<Product> lSaveProducts = ifSerializer.Deserialize(fdLoadFile) as List<Product>;
            fdLoadFile.Close();
            
//在界面中顯示反序列化後的結果
            foreach (Product pProduct in lSaveProducts)
            {
                txbResult.Text 
+= pProduct.ToString()+"\b\r";
            }            
        }
    }
}


結果顯示如下:


原文地址:https://www.cnblogs.com/scottckt/p/1234323.html