C#序列化与反序列化

2021-02-11 23:17

阅读:510

标签:释放   pen   main   ram   ace   serialize   close   cep   class   

一、序列化:

 1       public void SerilizeData()
 2         {
 3             FileStream fs = null;
 4             try
 5             {
 6                 MainOperator mainOperator = new MainOperator();//创建MainOperator类的对象
 7                 fs = new FileStream(Application.StartupPath+@"\test.obj", FileMode.Create);
 8                 BinaryFormatter formatter = new BinaryFormatter();
 9                 formatter.Serialize(fs, mainOperator); //对MainOperator 类进行序列化
10             }
11             catch (Exception ex)
12             {
13                 MessageBox.Show(this.GetType().Name, new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, ex.Message);
14             }
15             if (fs != null)
16             {
17                 fs.Close();//释放
18             }
19 
20         }

二、反序列化:

  private void DeserilizeData()
        {
          
            FileStream fs = null;
            try
            {
                fs = new FileStream(Application.StartupPath + @"\test.obj", FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                mainOperator = (MainOperator)formatter.Deserialize(fs);//对MainOperator类反序列化
            }
            catch (Exception ex)
            {}
            if (fs != null)
            {
                fs.Close();
            }

        }

 

C#序列化与反序列化

标签:释放   pen   main   ram   ace   serialize   close   cep   class   

原文地址:https://www.cnblogs.com/zhubaoming/p/8484373.html


评论


亲,登录后才可以留言!