二进制序列化简单介绍

本文详细介绍了如何使用BinaryFormatter进行二进制序列化和反序列化操作,包括使用命名空间、实例化BinaryFormatter、标记[Serializable]属性及具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二进制序列化:

  序列化就是将对象从内存中移到硬盘(使用FileStream)或者向网络(使用NetWorkStream)中传送。可认为是格式化数据。

  1 使用时先添加命名空间:

      using System.Runtime.Serialization.Formatters.Binary;

  2  BinaryFormatter bf = new BinaryFormatter();   实例化

  3 使用  [Serializable] 标记,将它添加到要序列化的对象上;

   例1:

 [Serializable]
    class Person
    {
        public int Num;
        public string Name;
    }

 static void Main(string[] args)
        {
            string path = @"D:\txt";  //找一个能够写入的路径,
            List<Person> personList = new  List<Person>(); //将Person类写成集合;
            Person ps = new Person();
            ps.Num = 10;
            ps.Name = "往";
            personList.Add(ps);
            //创建一个写入的文件流,  Path.Combine();将路径和文件名拼接

    //要添加命名空间  using System.IO;
            FileStream writer=new FileStream(Path.Combine(path,"ps.txt"),FileMode.Open,FileAccess.Write);
            using (writer)
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(writer, personList);
            }
            //序列化完成,那么怎样能读出?
            //反序列化
            FileStream Reader = new FileStream(Path.Combine(path, "ps.txt"), FileMode.Open, FileAccess.Read);
            using (Reader)
            {
                BinaryFormatter bf1 = new BinaryFormatter();
              
              personList = (List<Person>)bf1.Deserialize(Reader);
            }

    Console.ReadKey();

}

    例2:

    string path = @"D:\txt\ps.txt"; 

    List<int> lis = new List<int>() {1,2,3,4,5,6 };
            ////把对象二进制序列化;
            BinaryFormatter bf = new BinaryFormatter(); //序列化器
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Write);
            using(file)
            {
                bf.Serialize(file,lis);
            }

            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            using (file)
            {
                List<int> lis=(List<int>)bf.Deserialize(file);
                for (int i = 0; i < lis.Count; i++)
                {
                    Console.WriteLine(lis[i]);
                }
            }
            Console.ReadKey();

 

    

转载于:https://www.cnblogs.com/yingFly/archive/2012/07/03/BinaryFormatter.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值