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();
                }
  • 相关阅读:
    python反射
    numpy笔记
    leetcode43
    leetcode-42
    The Github Flow
    leetcode-37
    leetcode-41
    leetcode-40
    TCP扫盲2
    字节码分析与操作
  • 原文地址:https://www.cnblogs.com/liuhao2050/p/3804875.html
Copyright © 2011-2022 走看看