zoukankan      html  css  js  c++  java
  • 序列化与反序列化

    小鸟成长笔记;

    持久化:将对象的状态保存起来;

    序列化:将对象的状态持久化到存储设备中(磁盘);

    注意:1.要将类标记为[Serializable]才可以被序列化

       2.以二进制的方式序列化,而不是文本文档

     
        [Serializable]
        class Person
        {
            public string Name { get; set; }
            public int Age{ get; set; }
        }

    序列化

    static void Main(string[] args)
            {   
                Person p = new Person();
                p.Name="HaoLiu";
                p.Age=19;
               using(FileStream fs=new FileStream("se.bin",FileMode.Create)){
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bf.Serialize(fs, p);
               }
                
            }

    反序列化

     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf=new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                using(FileStream fs=new FileStream("se.bin",FileMode.Open)){
                    object obj = bf.Deserialize(fs);
                    Person p = obj as Person;//强制转换为Person对象
                    Console.WriteLine(p.Name+":"+p.Age);
                    Console.ReadKey();
                }
  • 相关阅读:
    C语言实现快排
    C语言实现双向循环链表
    mysql插入数据后返回自增ID的方法
    golang flag包简单例子
    练习题 (六)
    练习题 (五)
    练习题 (四)
    练习题 (三)
    练习题 (二)
    练习题 (一)
  • 原文地址:https://www.cnblogs.com/liuhao2050/p/3804875.html
Copyright © 2011-2022 走看看