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; }
                }
            }
  • 相关阅读:
    sed command
    【Python3】作用域(局部变量、全局变量)
    【Python3】函数与参数
    【Python3】编程范式
    【Python3】字符解码与编码
    【Python3】文件操作
    【Python3】集合
    【Python3】目录
    【Python3】字典
    【Python3】字符串操作
  • 原文地址:https://www.cnblogs.com/automation/p/2872526.html
Copyright © 2011-2022 走看看