C#序列化和反序列化

来源:互联网 发布:nginx 访问隐藏目录 编辑:程序博客网 时间:2024/04/27 08:40

 

实现目的:序列化和反序列化一个dataTable

加入一个名为Book的类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. using System.Data;
  6. namespace Rop
  7. {
  8.     [Serializable]              //标记一个类便可使之可序列化
  9.     public class Book
  10.     {
  11.         string name;
  12.         float price;
  13.         string author;
  14.         DataTable dt;
  15.         
  16.         public Book(string bookname, float bookprice, string bookauthor)
  17.         {
  18.             name = bookname;
  19.             price = bookprice;
  20.             author = bookauthor;
  21.         }
  22.         public Book()
  23.         {
  24.             dt = new DataTable();
  25.             dt.Columns.Add();
  26.             dt.Columns.Add();
  27.             dt.Columns.Add();
  28.             dt.Columns.Add();
  29.             dt.Columns.Add();
  30.         }
  31.         public void AddInformationToTable(Object[] arrStrng)
  32.         {
  33.             
  34.             dt.Rows.Add(arrStrng);
  35.         }
  36.         public DataTable getInformation()
  37.         {
  38.             return dt;
  39.         }
  40.     }
  41. }

序列化的使用代码

  1. //接着当然要创建一个文件了,这个文件就是用来存放我们要序列化的信息了.
  2.             FileStream fs = new FileStream(@"C:/book.dat", FileMode.Create);
  3.             //序列化的实现也很简单,like this:
  4.             BinaryFormatter formatter = new BinaryFormatter();
  5.             formatter.Serialize(fs, book);
  6.             fs.Close();

反序列化的使用代码

 

  1. Book book = new Book();
  2.             using (FileStream fs = new FileStream(@"C:/book.dat", FileMode.Open))
  3.             {
  4.                 BinaryFormatter formatter = new BinaryFormatter();
  5.                 book = (Book)formatter.Deserialize(fs);//在这里大家要注意咯,他的返回值是object
  6.                 DataTable dTab = book.getInformation();
  7.             } 

 

最后反序列化出的就是开始保存的DataTable

原创粉丝点击