BinaryFormatter序列化
来源:互联网 发布:网络项目管理课程 编辑:程序博客网 时间:2024/06/04 08:41
- BinaryFormatter序列化
- 来源:www.greensoftcode.net 发布日期:2009-08-21 点击次数:441 发布者IP:
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
}
}
- BinaryFormatter序列化
- 序列化之一 BinaryFormatter
- 使用BinaryFormatter进行序列化
- BinaryFormatter 序列化反序列化
- BinaryFormatter 序列化及反序列化
- 使用BinaryFormatter()序列化对象方法
- [C#]BinaryFormatter、SoapFormatter、XML3种序列化
- 解析C# BinaryFormatter实现序列化
- BinaryFormatter序列化实例(一)
- BinaryFormatter序列化实例(二)
- BinaryFormatter序列化实例(三)
- BinaryFormatter序列化实例(四)
- 对象序列化 BinaryFormatter、XmlSerializer、SoapFormatter
- BinaryFormatter、SoapFormatter、XML3种序列化
- SoapFormatter 和 BinaryFormatter 序列化对象
- MSDN|BinaryFormatter|序列化和反序列化|c#
- C# 二进制BinaryFormatter进行序列化与反序列化
- C# 二进制BinaryFormatter进行序列化与反序列化
- cocos2d-x中带光标的输入框(CCTextFieldTTF)(这个不完善,后期再继续研究)
- 表单的多种提交方式
- HTML5 坦克大战 游戏开发
- 多线程服务器的适用场合
- 生活随笔:生活是否淡了
- BinaryFormatter序列化
- Libvirt简介
- 图算法---单源最短路径
- smarty模板if语句整体运用
- 判断 iframe 是否加载完成(记录)
- 微软等数据结构+算法面试100题(5)--怎样编写一个程序,把一个有序整数数组放到二叉树中
- Linux命令行下编辑常用的快捷键
- java常见的面试题集锦(一)
- 黑马训练营-学习笔记----网络编程