C#序列化和還原序列化代碼

來源:互聯網
上載者:User

我們在日常開發中會經常用到序列化和還原序列化,他們到底是什麼意思呢?通俗的講序列化就是把對象轉化成資料檔案或者欄位(二進位或者XML),還原序列化就是資料檔案或者欄位轉化為資料對象。 下面我以提問題的方式,幫大家解釋一下序列化和還原序列化。(C#代碼為例)

一 、為什麼使用序列化和還原序列化?

  1.儲存對象。通常我們在C#代碼中構建了一個對象需要把該對象儲存到資料庫、檔案、Application、Session、Coockie、ViewState等其他儲存環境中,以備下次直接使用。

  2.共用資料. 對象僅在建立對象的應用程式定義域中有效,其他應用程式定義域想調用該對象資料就會使用該技術。

  3.在網路上傳送對象的位元組序列。其中Web Service就是一個典型的例證。

  4.在一些分布式系統中也經常會用到該技術。

二、序列化和還原序列化有哪些類型?

  在C#中序列化還原序列化類型大致有如下三種:

    第一、位元據(BinaryFormatter->IFormatter)

    第二、XML資料(XmlSerializer)

    第三、Soap資料(SoapFormatter->IFormatter)

三、序列化和還原序列化分別如何??   


/// <summary>
/// UserInfo for public test smaple
/// </summary>
[Serializable]
public class UserInfo
{

    #region Database fields
    private System.Int32 _UserID;
    private System.String _UserName;
    private System.Int16 _UserType;
    private System.String _Email;
    private System.String _Pwd;
    private System.String _Firstname;
    private System.String _Lastname;
    #endregion

    #region GETs and SETs

    public System.Int32 UserID
     {
        get { return _UserID; }
        set { _UserID = value; }
     }

    public System.String UserName
     {
        get { return _UserName; }
        set { _UserName = value; }
     }

    public System.Int16 UserType
     {
        get { return _UserType; }
        set { _UserType = value; }
     }

    public System.String Email
     {
        get { return _Email; }
        set { _Email = value; }
     }

    public System.String Pwd
     {
        get { return _Pwd; }
        set { _Pwd = value; }
     }
    public System.String Firstname
     {
        get { return _Firstname; }
        set { _Firstname = value; }
     }

    public System.String Lastname
     {
        get { return _Lastname; }
        set { _Lastname = value; }
     }
    #endregion
    
    public UserInfo()
     {
     }
}

第一、位元據        


    public static byte[] Serialize(UserInfo usr)
     {
         IFormatter formatter = new BinaryFormatter();
         MemoryStream ms = new MemoryStream();
        byte[] b;
         formatter.Serialize(ms, usr);
         ms.Position = 0;
         b = new byte[ms.Length];
         ms.Read(b, 0, b.Length);
         ms.Close();
        return b;
     }
public static UserInfo Deserialize(byte[] byteArray)
     {
         IFormatter formatter = new BinaryFormatter();
         MemoryStream ms = new MemoryStream();
         ms.Write(byteArray, 0, byteArray.Length);
         ms.Position = 0;
         UserInfo usr = formatter.Deserialize(ms) as UserInfo;
        return usr;
     }

第二、Xml資料


    public static XmlDocument Serialize(UserInfo usr)
     {
         XmlSerializer lizer = new XmlSerializer(usr.GetType());
         MemoryStream ms = new MemoryStream();
         lizer.Serialize(ms, usr);
         XmlDocument doc=new XmlDocument();
         doc.Load(ms);
        return doc;
     }
    public static UserInfo DeserializeXml(XmlDocument doc)
     {
         XmlSerializer lizer = new XmlSerializer(typeof(UserInfo));
         StringReader reader = new StringReader(doc.OuterXml);
         UserInfo usr = lizer.Deserialize(reader) as UserInfo;
        return usr;
     }       

第三、Soap資料


    static void Serialize()
     {
        // Create a hashtable of values that will eventually be serialized.
         Hashtable addresses = new Hashtable();
         addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
         addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
         addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable (and its key/value pairs),
        // you must first open a stream for writing.
        // Use a file stream here.
         FileStream fs = new FileStream("DataFile.soap", FileMode.Create);

        // Construct a SoapFormatter and use it
        // to serialize the data to the stream.
         SoapFormatter formatter = new SoapFormatter();
        try
         {
             formatter.Serialize(fs, addresses);
         }
        catch (SerializationException e)
         {
             Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
         }
        finally
         {
             fs.Close();
         }
     }


static void Deserialize()
     {
        // Declare the hashtable reference.
         Hashtable addresses  = null;

        // Open the file containing the data that you want to deserialize.
         FileStream fs = new FileStream("DataFile.soap", FileMode.Open);
        try
         {
             SoapFormatter formatter = new SoapFormatter();

            // Deserialize the hashtable from the file and
            // assign the reference to the local variable.
             addresses = (Hashtable) formatter.Deserialize(fs);
         }
        catch (SerializationException e)
         {
             Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
         }
        finally
         {
             fs.Close();
         }

        // To prove that the table deserialized correctly,
        // display the key/value pairs to the console.
        foreach (DictionaryEntry de in addresses)
         {
             Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);

聯繫我們

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