实现目的:序列化和反序列化一个dataTable
加入一个名为Book的类
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Collections;
- using System.Data;
- namespace Rop
- {
- [Serializable] //标记一个类便可使之可序列化
- public class Book
- {
- string name;
- float price;
- string author;
- DataTable dt;
- public Book(string bookname, float bookprice, string bookauthor)
- {
- name = bookname;
- price = bookprice;
- author = bookauthor;
- }
- public Book()
- {
- dt = new DataTable();
- dt.Columns.Add();
- dt.Columns.Add();
- dt.Columns.Add();
- dt.Columns.Add();
- dt.Columns.Add();
- }
- public void AddInformationToTable(Object[] arrStrng)
- {
- dt.Rows.Add(arrStrng);
- }
- public DataTable getInformation()
- {
- return dt;
- }
- }
- }
序列化的使用代码
- //接着当然要创建一个文件了,这个文件就是用来存放我们要序列化的信息了.
- FileStream fs = new FileStream(@"C:/book.dat", FileMode.Create);
- //序列化的实现也很简单,like this:
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(fs, book);
- fs.Close();
反序列化的使用代码
- Book book = new Book();
- using (FileStream fs = new FileStream(@"C:/book.dat", FileMode.Open))
- {
- BinaryFormatter formatter = new BinaryFormatter();
- book = (Book)formatter.Deserialize(fs);//在这里大家要注意咯,他的返回值是object
- DataTable dTab = book.getInformation();
- }
最后反序列化出的就是开始保存的DataTable