整容说文库 > 程序代码 > 教育资讯

求高人露一下源码:C#序列化一个类,和反序列化(恢复)一个类的源码,怎么写。

来源:学生作业帮助网 编辑:整容说文库 时间:2020/07/16 08:41:03 程序代码
求高人露一下源码:C#序列化一个类,和反序列化(恢复)一个类的源码,怎么写。程序代码
如题
using System.Runtime.Serialization.Formatters.Binary;


   /// <summary>
        /// 序列化对象到BYTE         
        /// <param name="p_Object"></param>
        /// <returns></returns>
        public static byte[] ObjectToBytes(object p_Object)
        {
            BinaryFormatter _Formatter = new BinaryFormatter();           
            MemoryStream _Memory = new MemoryStream();
            try
            {
                _Formatter.Serialize(_Memory, p_Object);
            }
            catch (Exception ex)
            {              
            }
            return _Memory.GetBuffer();
        }

        /// <summary>
        /// 反序列 bytes到对象
        /// </summary>
        /// <param name="p_ObjectBytes"></param>
        /// <returns></returns>
        public static object BytesToObject(byte[] p_ObjectBytes)
        {
            BinaryFormatter _Formatter = new BinaryFormatter();
            MemoryStream _MemStr = new MemoryStream(p_ObjectBytes);
            try
            {
                return _Formatter.Deserialize(_MemStr);
            }
            catch (Exception ex)
            {               
                return null;
            }
        }
哎.上网找个序列化的例子看一下不就得了.
msdn 上不有么
引用 1 楼 zgke 的回复:
using System.Runtime.Serialization.Formatters.Binary; 
  
  
    ///  <summary> 
         /// 序列化对象到BYTE          
         ///  <param name="p_Object"> </param> 
         ///  <returns> </returns> 
         public static byte[] ObjectToBytes(object p_Object) 
         { 
             BinaryFormatter _Formatter = new BinaryFormatter();            
             MemoryStream _Memory = new Me…


我把你的代码应用测试了一下,有点问题,帮忙一下:

以下代码测试环境:
两个Button:button_ObjectSerializeToBinary,button_BinaryToObject
四个RichTextBox:richTextBox1_Message,richTextBox1_Result,richTextBox2_Message,richTextBox2_Result
InitialzeComponent();代码和控件声明

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.richTextBox1_Message = new System.Windows.Forms.RichTextBox();
            this.button_ObjectSerializeToBinary = new System.Windows.Forms.Button();
            this.richTextBox1_Result = new System.Windows.Forms.RichTextBox();
            this.richTextBox2_Message = new System.Windows.Forms.RichTextBox();
            this.richTextBox2_Result = new System.Windows.Forms.RichTextBox();
            this.button_BinaryToObject = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.button_ObjectSerializeToBinary);
            this.groupBox1.Controls.Add(this.richTextBox1_Result);
            this.groupBox1.Controls.Add(this.richTextBox1_Message);
            this.groupBox1.Location = new System.Drawing.Point(12, 3);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(548, 196);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "对象二进制化";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.button_BinaryToObject);
            this.groupBox2.Controls.Add(this.richTextBox2_Message);
            this.groupBox2.Controls.Add(this.richTextBox2_Result);
            this.groupBox2.Location = new System.Drawing.Point(12, 205);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(548, 223);
            this.groupBox2.TabIndex = 0;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "二进制对象化";
            // 
            // richTextBox1_Message
            // 
            this.richTextBox1_Message.Location = new System.Drawing.Point(7, 21);
            this.richTextBox1_Message.Name = "richTextBox1_Message";
            this.richTextBox1_Message.Size = new System.Drawing.Size(249, 169);
            this.richTextBox1_Message.TabIndex = 0;
            this.richTextBox1_Message.Text = "";
            // 
            // button_ObjectSerializeToBinary
            // 
            this.button_ObjectSerializeToBinary.Location = new System.Drawing.Point(262, 91);
            this.button_ObjectSerializeToBinary.Name = "button_ObjectSerializeToBinary";
            this.button_ObjectSerializeToBinary.Size = new System.Drawing.Size(33, 23);
            this.button_ObjectSerializeToBinary.TabIndex = 1;
            this.button_ObjectSerializeToBinary.Text = ">>";
            this.button_ObjectSerializeToBinary.UseVisualStyleBackColor = true;
            this.button_ObjectSerializeToBinary.Click += new System.EventHandler(this.button_ObjectSerializeToBinary_Click);
            // 
            // richTextBox1_Result
            // 
            this.richTextBox1_Result.Location = new System.Drawing.Point(301, 21);
            this.richTextBox1_Result.Name = "richTextBox1_Result";
            this.richTextBox1_Result.Size = new System.Drawing.Size(241, 169);
            this.richTextBox1_Result.TabIndex = 0;
            this.richTextBox1_Result.Text = "";
            // 
            // richTextBox2_Message
            // 
            this.richTextBox2_Message.Location = new System.Drawing.Point(7, 20);
            this.richTextBox2_Message.Name = "richTextBox2_Message";
            this.richTextBox2_Message.Size = new System.Drawing.Size(249, 169);
            this.richTextBox2_Message.TabIndex = 0;
            this.richTextBox2_Message.Text = "";
            // 
            // richTextBox2_Result
            // 
            this.richTextBox2_Result.Location = new System.Drawing.Point(301, 20);
            this.richTextBox2_Result.Name = "richTextBox2_Result";
            this.richTextBox2_Result.Size = new System.Drawing.Size(241, 169);
            this.richTextBox2_Result.TabIndex = 0;
            this.richTextBox2_Result.Text = "";
            // 
            // button_BinaryToObject
            // 
            this.button_BinaryToObject.Location = new System.Drawing.Point(262, 90);
            this.button_BinaryToObject.Name = "button_BinaryToObject";
            this.button_BinaryToObject.Size = new System.Drawing.Size(33, 23);
            this.button_BinaryToObject.TabIndex = 1;
            this.button_BinaryToObject.Text = ">>";
            this.button_BinaryToObject.UseVisualStyleBackColor = true;
            this.button_BinaryToObject.Click += new System.EventHandler(this.button_BinaryToObject_Click);
            // 
            // SerializeClassToBinary
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(572, 440);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "SerializeClassToBinary";
            this.Text = "SerializeClassToBinary";
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button button_ObjectSerializeToBinary;
        private System.Windows.Forms.RichTextBox richTextBox1_Result;
        private System.Windows.Forms.RichTextBox richTextBox1_Message;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Button button_BinaryToObject;
        private System.Windows.Forms.RichTextBox richTextBox2_Message;
        private System.Windows.Forms.RichTextBox richTextBox2_Result;



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace TestApplication.SerializeTest
{
    public partial class SerializeClassToBinary : Form
    {
        public SerializeClassToBinary()
        {
            InitializeComponent();
        }

        /// <summary> 
        /// 序列化对象到BYTE        
        /// <param name="p_Object"> </param> 
        /// <returns> </returns> 
        public static byte[] ObjectToBytes(object p_Object)
        {
            BinaryFormatter _Formatter = new BinaryFormatter();
            MemoryStream _Memory = new MemoryStream();
            try
            {
                _Formatter.Serialize(_Memory, p_Object);
            }
            catch (Exception ex)
            {
            }
            return _Memory.GetBuffer();
        }

        /// <summary> 
        /// 反序列 bytes到对象 
        /// </summary> 
        /// <param name="p_ObjectBytes"> </param> 
        /// <returns> </returns> 
        public static object BytesToObject(byte[] p_ObjectBytes)
        {
            BinaryFormatter _Formatter = new BinaryFormatter();
            MemoryStream _MemStr = new MemoryStream(p_ObjectBytes);
            try
            {
                return _Formatter.Deserialize(_MemStr);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return null;
            }
        }

        class MyClass
        {
            public MyClass()
            {
                Name = "Jave";
                NickName = "JaveLin";
                Age = 22;
            }

            private string _name;

            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            private string _nickName;

            public string NickName
            {
                get { return _nickName; }
                set { _nickName = value; }
            }

            private int _age;

            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }

        }

        private void button_ObjectSerializeToBinary_Click(object sender, EventArgs e)
        {
            //对象二进制化
            byte[] bytes = ObjectToBytes(new MyClass());
            this.richTextBox1_Message.Text = "MyClass 序列化成功。结果显示在右边的RichTextBox里。";
            foreach (byte b in bytes)
            {
                this.richTextBox1_Result.Text += b.ToString() + ",";
            }
        }

        private void button_BinaryToObject_Click(object sender, EventArgs e)
        {
            //二进制对象化
            string Content = this.richTextBox1_Result.Text;
            int Count = 0;
            string[] Contents = Content.Split(new char[] { ',' });
            Count = Contents.Length - 1;
            byte[] bytes = new byte[Count];
            for (int i = 0; i < Count; i++)
            {
                bytes[i] = Convert.ToByte(Contents[i]);
            }
            object myClass = BytesToObject(bytes);
            MyClass one = myClass as MyClass;
            MessageBox.Show(one.GetType().ToString() + " Success.");
            this.richTextBox2_Message.Text = "MyClass 反序列化成功。结果显示在右边的RichTextBox里。";
        }
    }
}



当我点击这个序列化对象是,可以成功运行,但是就是在反序列化该对象时,就有错了。
错误就在:BytesToObject()方法里的:return _Formatter.Deserialize(_MemStr);这行代码

最后catch里的ex对象的值是:
+ ex {"二进制流“0”不包含有效的 BinaryHeader。这可能是由于无效流,或由于在序列化和反序列化之间的对象版本更改。"} System.Exception {System.Runtime.Serialization.SerializationException}


运行图片:


如果图片看不到。请右键该图片位置,查看属性,复制URL到地址,回车,即可看到。
你序列化的类需要一个特性

        [Serializable]
        class MyClass
        {
            public MyClass()
            {
                Name = "Jave";
                NickName = "JaveLin";
                Age = 22;
            }

            private string _name;

            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            private string _nickName;

            public string NickName
            {
                get { return _nickName; }
                set { _nickName = value; }
            }

            private int _age;

            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }

        }
引用 6 楼 zgke 的回复:
你序列化的类需要一个特性 
  
         [Serializable] 
         class MyClass 
         { 
             public MyClass() 
             { 
                 Name = "Jave"; 
                 NickName = "JaveLin"; 
                 Age = 22; 
             } 
  
             private string _name; 
  
             public string Name 
             { 
                 get { return _name; } 
             …


大哥。

我要想对一些已经封装好的DLL里的某个类序列化呢?

这时我不可以修改这个类的新特性了。因为DLL里的是保护资源。

那我该怎么办?

有方法解决吗?
使用XML序列化把

 System.Xml.Serialization.XmlSerializer _XML = new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
            MemoryStream _Memory =new MemoryStream();
            _XML.Serialize(_Memory, new MyClass());

            _Memory.Position = 0;
            object a =_XML.Deserialize(_Memory);
SOAP

XML

二进制 



要那种方式的,,百度一下,多!
程序代码