.NET序列化與還原序列化

來源:互聯網
上載者:User

.net提供了三種序列化方式:

1.XML Serialize

2.Soap Serialize

3.Binary Serialize

第一種序列化方式對有些類型不能夠序列化,如hashtable;我主要介紹後兩種類型得序列化

一.Soap Serialize

使用SoapFormatter.Serialize()實現序列化.SoapFamatter在System.Runtime.Serialization.Formatters.Soap命名空間下,使用時需要引用System.Runtime.Serialization.Formatters.Soap.dll.它可將對象序列化成xml.

[Serializable]
  public class Option:ISerializable
  {
//此建構函式必須實現,在還原序列化時被調用.
   public Option(SerializationInfo si, StreamingContext context)
   {
    this._name=si.GetString("NAME");
    this._text=si.GetString("TEXT");
    this._att =(MeteorAttributeCollection)si.GetValue("ATT_COLL",typeof(MeteorAttributeCollection));
   }
   public Option(){_att = new MeteorAttributeCollection();}
   public Option(string name,string text,MeteorAttributeCollection att)
   {
    _name = name;
    _text = text;
    _att = (att == null ? new MeteorAttributeCollection():att);
   }
   private string _name;
   private string _text;
   private MeteorAttributeCollection _att;
   /// <summary>
   /// 此節點名稱
   /// </summary>
   public String Name
   {
    get{return this._name;}
    set{this._name =value;}
   }
   /// <summary>
   /// 此節點文本值
   /// </summary>
   public String Text
   {
    get{return this._text;}
    set{this._text =value;}
   }
   /// <summary>
   /// 此節點屬性
   /// </summary>
   public MeteorAttributeCollection AttributeList
   {
    get{return this._att;}
    set{this._att=value;}
   }
///此方法必須被實現
   public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
   {
    info.AddValue("NAME",this._name);
    info.AddValue("TEXT",this._text);
    info.AddValue("ATT_COLL",this._att,typeof(MeteorAttributeCollection));
   }
}
在這個類中,紅色部分為必須實現的地方.否則在序列化此類的時候會產生異常“必須被標註為可序列化“,“未找到還原序列化類型Option類型對象的建構函式“等異常

*****************************

下面是序列化與還原序列化類 MeteorSerializer.cs

************************

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;

namespace Maxplatform.Grid
{
 /// <summary>
 /// 提供多種序列化對象的方法(SoapSerializer,BinarySerializer)
 /// </summary>
 public class MeteorSerializer
 {
  public MeteorSerializer()
  {
  
  }
 
  #region Soap
  /// <summary>
  /// Soap格式的序列化
  /// </summary>
  /// <param name="o"></param>
  /// <returns></returns>
  public static string SoapSerializer(object o)
  {
   // To serialize the hashtable and its key/value pairs, 
   // you must first open a stream for writing.
   // In this case, use a file stream.
   //FileStream fs = new FileStream("DataFile.xml", FileMode.Create);
   Stream ms=new MemoryStream();
   // Construct a BinaryFormatter and use it to serialize the data to the stream.
   SoapFormatter formatter = new SoapFormatter();
   try
   {
    formatter.Serialize(ms, o);
  
    byte[] b=new byte[ms.Length];
    ms.Position=0;
    ms.Read(b,0,b.Length);
               
    string s=Convert.ToBase64String(b);
    return s;
   }
   catch (SerializationException e)
   {
    //Log.Write("ServiceNode:Exception","Failed to serialize. Reason: " + e.Message);
    throw e;
   }
   finally
   {
    ms.Close();
   }

  }
  /// <summary>
  /// Soap格式的還原序列化
  /// </summary>
  /// <param name="returnString"></param>
  /// <returns></returns>
  public static object SoapDeserialize(string returnString)
  {

   // Open the file containing the data that you want to deserialize.
   SoapFormatter formatter;
   MemoryStream ms=null;
   try
   {
    formatter = new SoapFormatter();

    byte[] b=Convert.FromBase64String(returnString);

    ms=new MemoryStream(b);
   
    // Deserialize the hashtable from the file and
    // assign the reference to the local variable.
    object o = formatter.Deserialize(ms);
    return o;
   }
   catch (SerializationException e)
   {
    //Log.Write("ServiceNode:Exception","Failed to deserialize. Reason: " + e.Message);
    throw e;
   }
   finally
   {
    ms.Close();
   
   }

  }
  #endregion

  #region Binary
  /// <summary>
  /// Binary格式的序列化
  /// </summary>
  /// <param name="o"></param>
  /// <returns></returns>
  public static string BinarySerializer(object o)
  {
   // To serialize the hashtable and its key/value pairs, 
   // you must first open a stream for writing.
   // In this case, use a file stream.
   //FileStream fs = new FileStream("DataFile.xml", FileMode.Create);
   Stream ms=new MemoryStream();
   // Construct a BinaryFormatter and use it to serialize the data to the stream.
   BinaryFormatter formatter = new BinaryFormatter();
   try
   {
    formatter.Serialize(ms, o);
  
    byte[] b=new byte[ms.Length];
    ms.Position=0;
    ms.Read(b,0,b.Length);
               
    string s=Convert.ToBase64String(b);
    return s;
   }
   catch (SerializationException e)
   {
    //Log.Write("ServiceNode:Exception","Failed to serialize. Reason: " + e.Message);
    throw e ;
   }
   finally
   {
    ms.Close();
   }

  }
  /// <summary>
  /// Binary格式的還原序列化
  /// </summary>
  /// <param name="returnString"></param>
  /// <returns></returns>
  public static object BinaryDeserialize(string returnString)
  {

   // Open the file containing the data that you want to deserialize.
   BinaryFormatter formatter;
   MemoryStream ms=null;
   try
   {
    formatter = new BinaryFormatter();

    byte[] b=Convert.FromBase64String(returnString);

    ms=new MemoryStream(b);
   
    // Deserialize the hashtable from the file and
    // assign the reference to the local variable.
    object response = formatter.Deserialize(ms);
    return response;
   }
   catch (SerializationException e)
   {
    //Log.Write("ServiceNode:Exception","Failed to deserialize. Reason: " + e.Message);
    throw e;
   }
   finally
   {
    ms.Close();
   
   }

  }
  #endregion

 

 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.