實體類的二進位序列化

來源:互聯網
上載者:User

在.NET中,我們可以將對象序列化從而儲存對象的狀態到記憶體或者磁碟檔案中,或者分布式應用程式中用於系統通訊,一般來說,二進位序列化的效率要高,所獲得的位元組數最小,我們來看看下面的例子:

 

private static void Main(string[] args)
{
  MemoryStream ms = null;
  Customer customer = Customer.GetOneCustomer();
  using (ms = new MemoryStream())
  {
      var formater = new BinaryFormatter();
      formater.Serialize(ms, customer);
      Console.WriteLine("BinaryFormatter Length:{0}", ms.Length);
  }
  using (ms = new MemoryStream())
  {
      var serializer = new XmlSerializer(typeof (Customer));
      serializer.Serialize(ms, customer);
      Console.WriteLine("XmlSerializer Length:{0}", ms.Length);
  }

PDF.NET(PWMIS資料開發架構)的實體類也提供了二進位序列化功能,下面我們來示範一下它的使用:

 

            //PDF.NET 實體類序列化、還原序列化測試
            Customer customer = new Customer();
            customer.CustomerBirthday = new DateTime(1999, 1, 1);
            customer.CustomerName = "張三";
            customer.CustomerMobile = "13011111111";
            //序列化
            byte[] buffer=  PdfNetSerialize.BinarySerialize(customer);
            string tempString= Convert.ToBase64String(buffer);            //還原序列化
            byte[] buffer2 = Convert.FromBase64String(tempString);
            //WFT_Customer customer2=(WFT_Customer) PdfNetSerialize.BinaryDeserialize(buffer2, typeof(WFT_Customer));
            Customer customer2 = GetEntity<Customer>(buffer2);

上面的例子使用了Base64來將序列化後的位元組數群組轉換成字串,從而利於使用。如果想將二進位位元組數組轉直接換成字串,可以使用具有8位編碼的字元集轉換,但不能使用其它字元集,比如Unicode、GB2312.

 

public string ConvertToString(object targetObject){
        //ISO8859-1 字串,8位,只有這種可以完整保留二進位
        Encoding _encoding = Encoding.GetEncoding(28591);
        byte[] buffer= PdfNetSerialize.BinarySerialize((EntityBase)targetObject);
        return _encoding.GetString(buffer);
}

 

為了更通用,定義了一個GetEntity泛型方法,從二進位位元組流還原序列化獲得一個實體類:

 

        T GetEntity<T>(byte[] buffer ) where T:EntityBase 
        {
            return (T)PdfNetSerialize.BinaryDeserialize(buffer, typeof(T));
        }

 

所以,PDF.NET架構的序列化功能使用很簡單,而且也有很高的效率。利用二進位序列化,可以將一個實體物件集合持久化到磁碟,這樣就有可能做出一個“對象資料庫”了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.