• 序列化与反序列化


    小鸟成长笔记;

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

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

    注意: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();
                }
  • 相关阅读:
    输入和输出

    4. 深入 Python 流程控制
    js下拉框选择图片
    按下enter触发事件
    js多种方法取数组的最后一个元素
    apply,call,bind函数作用与用法
    vue中的js绑定样式
    js添加删除class
    rem等比例自适应手机尺寸
  • 原文地址:https://www.cnblogs.com/liuhao2050/p/3804875.html
Copyright © 2020-2023  润新知