使用BinaryFormatter类序列化

(一)

 有时候需要将C#中某一个结构很复杂的类的对象存储起来,或者通过网路传输到远程的客户端程序中去, 这时候用文件方式或者数据库方式存储或者传送就比较麻烦了,这个时候,最好的办法就是使用串行和解串(Serialization & Deserialization).


.NET中串行有三种,BinaryFormatter, SoapFormatter和XmlSerializer. 

其中BinaryFormattter最简单,它是直接用二进制方式把对象(Object)进行串行或反串,他的优点是速度快,可以串行private或者protected的member, 在不同版本的。NET中都兼容,可以看作是。NET自己的本命方法,当然缺点也就随之而来了,离开了。NET它就活不了,所以不能在其他平台或跨网路上进行。

运用BinaryFormatter的步骤也相当直观和简单。

1。在你需要串行的类里,用[Serializable]声明这个类是可以串行的,当然有些不想被串行的元素,可以用[NonSerialized]属性来屏蔽。如果有些元素是新版本中添加的,可以用属性[FieldOption]来增加兼容性。

2。生成一个流Stream, 里面包含你想存储数据的文件或者网络流.

3。创建一个BinaryFormatter类的Object.

4。然后就可以直接用方法Serialize/Deserialize来串行或者反串了。(注意这两个方法不是static的,所以你非得建立一个对象不可)。

举例如下:
串行:

FileStream fs = new FileStream("SerializedDate.data", FileMode.Create);
BinaryFormatter bf = New BinaryFormatter();
// Here is the object that you want to be serialized
MyClass mc = new MyClass();
// here put something in mc.
bf.Serialize(fs, mc);
fs.Close();

反串行:

FileStream fs = new FileStream("SerializedDate.data", FileMode.Open);
BinaryFormatter bf = New BinaryFormatter();
MyClass mc = new MyClass();  // used to restore the object
mc = (MyClass)bf.Deserialize(fs);
fs.Close();

就这么简单。

(二)

BinaryFormatter序列化

序列化简单点来理解就是把内存的东西写到硬盘中,当然也可以写到内存中(这个内容我会在后面写一个例子).而反序列化就是从硬盘中把信息读到内存中.就这么简单,呵呵,现在来看下面的例子吧!

在这篇文章中我将使用BinaryFormatter序列化类Book作为例子,希望大家能从例子中深刻体会什么是序列化.

定义类Book:

 [Serializable]
 public class Book
 {
  string name;
  float    price;
  string author;

  public Book(string bookname, float bookprice, string bookauthor)
  {
   name = bookname;
   price = bookprice;
   author = bookauthor;
  }
 }

在类的上面增加了属性:Serializable.(如果不加这个属性,将抛出SerializationException异常).

通过这个属性将Book标志为可以序列化的.当然也有另一种方式使类Book可以序列化,那就是实行ISerializable接口了.在这里大家要注意了:Serializable属性是不能被继承的咯!!!

如果你不想序列化某个变量,该怎么处理呢?很简单,在其前面加上属性[NonSerialized] .比如我不想序列化

string author;

那我只需要

[NonSerialized]

string author;

好了,现在就告诉大家怎么实现序列化:

我们使用namespace:

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

首先创建Book实例,like this: 

 Book book = new Book("Day and Night", 30.0f, "Bruce");

接着当然要创建一个文件了,这个文件就是用来存放我们要序列化的信息了.

FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create);

序列化的实现也很简单,like this:

    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, book);

很简单吧!现在我列出整个原代码,包括反序列化.

  static void Main(string[] args)
  {
   Book book = new Book("Day and Night", 30.0f, "Bruce");

   using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create))
   {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, book);
   }

   book = null;

   using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Open))
   {
    BinaryFormatter formatter = new BinaryFormatter();
    book = (Book)formatter.Deserialize(fs);//在这里大家要注意咯,他的返回值是object
   }
  }

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lirushuokeyi/archive/2009/06/15/4271237.aspx

原文地址:https://www.cnblogs.com/zhuawang/p/2087652.html