31.序列化和反序列化

序列化和反序列化

序列化:就是将对象转换为二进制
反序列化:就是将二进制转换为对象

作用

传输数据。

如何序列化

1)、将这个类标记为可以被序列化的
2)、创建序列化对象BinaryFormatter
3)、调用序列化方法Serialize()

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;


namespace Demo {

    

    class Program {

        static void Main(string[] args) {

            //要将p这个对象 传输给对方电脑
            Person p = new Person();
            p.Name = "张三";
            p.Age = 19;
            
            using (FileStream fsWrite = new FileStream(@"C:Users22053Desktop
ew.txt", FileMode.OpenOrCreate, FileAccess.Write)) {
                //开始序列化对象
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fsWrite, p);
            }
            Console.WriteLine("序列化成功");
            Console.ReadKey();

        }


    }

    [Serializable]
    class Person {
        private string _name;
        private int _age;
        
        public string Name {
            get;
            set;
        }

        public int Age {
            get;
            set;
        }
    }

}

如何反序列化

1)、将这个类标记为可以被序列化的
2)、创建序列化对象BinaryFormatter
3)、调用反序列化方法Deserialize()

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;


namespace Demo {

    

    class Program {

        static void Main(string[] args) {

            //接收对方发送过来的二进制 反序列化成对象
            Person p;
            using (FileStream fsRead = new FileStream(@"C:Users22053Desktop
ew.txt", FileMode.OpenOrCreate, FileAccess.Read)) {
                BinaryFormatter bf = new BinaryFormatter();
                p = (Person)bf.Deserialize(fsRead);
            }
            Console.WriteLine(p.Name);
            Console.WriteLine(p.Age);
            Console.ReadKey();

        }


    }

    [Serializable]
    class Person {
        private string _name;
        private int _age;
        
        public string Name {
            get;
            set;
        }

        public int Age {
            get;
            set;
        }
    }

}

运行结果:

原文地址:https://www.cnblogs.com/lz32158/p/12923931.html