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; }
                }
            }
  • 相关阅读:
    C#实战Microsoft Messaging Queue(MSMQ)消息队列(干货)
    实现动态的XML文件读写操作(依然带干货)
    多线程下访问控件的方式(您一定会用到,附源码啦!)
    Microsoft.VisualBasic.dll的妙用(开发中肯定会用到哦)
    vue使用element-ui的el-input监听不了键盘事件解决
    vue强制刷新组件
    asp.net微信公众平台本地调试设置
    武大女硕士面试被拒,改简历冒充本科生找工作的感想(原创)
    完整的站内搜索Demo(Lucene.Net+盘古分词)
    ASP.NET多线程下使用HttpContext.Current为null解决方案
  • 原文地址:https://www.cnblogs.com/automation/p/2872526.html
Copyright © 2011-2022 走看看