BinaryFormatter探讨

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace TestBinaryFormatter
{
    class Program
    {
        static void Main(string[] args)
        {
            //序列化 从内存读取信息流
            Book book = new Book("Shikyoh", 600, "lcc");
            using (FileStream stream = new FileStream(@"E:\test.bat", FileMode.Create))
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, book);
            }
            Console.WriteLine("序列化成功,文档已生成");
            //反序列化 从信息流加载到内存中
            Book newBook = null;
            using (FileStream stream = new FileStream(@"E:\test.bat", FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                newBook = (Book)formatter.Deserialize(stream);

            }
            Console.WriteLine("读出来的信息:" + newBook.Name + "," + newBook.Price + "," + newBook.Author);
        }
    }
    [Serializable]
    public class Book
    {
        public string Name;
        public float Price;
        public string Author;
        public Book(string name, float price, string author)
        {
            Name = name;
            Price = price;
            Author = author;
        }
    }
}


参考:

有时候需要将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的,所以你非得建立一个对象不可)。

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

posted @ 2012-03-16 12:09  Shikyoh  阅读(2534)  评论(0编辑  收藏  举报