zoukankan      html  css  js  c++  java
  • 文件序列化和反序列化

    序列化是把对象以二进制的形式存在文件中

     List<Person> ps = new List<Person>();
                ps.Add(new Person("张三", 12, '男'));
                //能不能直接把对象,以二进制的形式存在文件中呢?
                FileStream fs = new FileStream(@"d:\序列化", FileMode.Create, FileAccess.Write);
                using (fs)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(fs, ps);
                } 

    反序列化:

    FileStream fs = new FileStream(@"d:\序列化", FileMode.Open, FileAccess.Read);
                List<Person> ps;
                using (fs)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    ps = (List<Person>)bf.Deserialize(fs);
    
                }
    注意:要序列化类必须打上 [Serializable]
    [Serializable]
            class Person
            {
                private string name;
                private int age;
                private char sex;
                public Person(string name, int age, char sex)
                {
                    this.name = name;
                    this.age = age;
                    this.sex = sex;
                }
                public void SayHello()
                {
                    Console.WriteLine("大家好,我是{0},今年{1}岁了,我是{2}生",name,age,sex);
                }
                public string Name
                {
                    get { return name; }
                    set { name = value; }
                }
                public int Age
                {
                    get { return age; }
                    set { age = value; }
                }
                public char Sex
                {
                    get { return sex; }
                    set { sex = value; }
                }
            }
  • 相关阅读:
    python开源项目
    Appscan 10用户安装手册
    20201201-k8s的node节点和独立nginx部署会冲突
    k8s-更换证书(apiserver新添加了VIP)
    20201224-修改pod网段(calico)
    深-宝的一梦
    洛谷-P3383 【模板】线性筛素数
    洛谷-P3913 车的攻击
    洛谷-P1866 编号
    洛谷-P1100 高低位交换
  • 原文地址:https://www.cnblogs.com/automation/p/2872526.html
Copyright © 2011-2022 走看看