C#序列化和反序列化
2008-11-13 14:55
323 查看
实现目的:序列化和反序列化一个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
加入一个名为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
相关文章推荐
- C#对 Json的序列化和反序列化会出现“k_BackingField”
- C#中XML与对象之间的序列化、反序列化
- C#中的序列化和反序列化是什么、有什么作用、使用方法详解
- (转)深入C#学习系列一:序列化(Serialize)、反序列化(Deserialize)
- C#强化系列文章七:序列化和反序列化
- 一个经过改良的XMLHelper(包含了序列化,反序列化,创建xml文件,读取节点,C#对象与xml文件的相互转换等等。)
- C# SerializableDictionary序列化/反序列化
- C#序列化、反序列化学习
- c# Json 自定义类作为字典键时,序列化和反序列化的处理方法
- c#中对object进行序列化和反序列化
- C# - 序列化和反序列化
- [转]深入C#学习系列一:序列化(Serialize)、反序列化(Deserialize)
- 在C#中实现Json的序列化与反序列化
- C# 序列化和反序列化
- C#中json字符串的序列化和反序列化
- C# JSON 序列化和反序列化——JavaScriptSerializer实现
- 深入C#学习系列一:序列化(Serialize)、反序列化(Deserialize)
- C#序列化,反序列化(Serialize,Deserialize)
- c# XML-Object对象 序列化-反序列化
- JAVA与c#的序列化和反序列化