对象序列化

对象序列化是将对象转换为二进制数据(字节流),反序列化是将二进制数据还原为对象,对象是稍纵即逝的,不仅程序重启、操作系统重启会使对象消逝,

就是退出函数的范围都可能造成对象的丢失,序列化/反序列化是为了保值对象持久化

下面是一个序列化和反序列化的例子

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //首先序列化
            //person p = new person();
            //p.Name = "张三";
            //p.Age = 12;

            //using (FileStream fs = new FileStream("1.txt", FileMode.Create, FileAccess.Write))
            //{
            //    BinaryFormatter bf = new BinaryFormatter();
            //    bf.Serialize(fs, p);
            //}
            //Console.WriteLine("完成");
            //Console.ReadKey();


            //下面是反序列化,获取对象
            using (FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
             object obj= bf.Deserialize(fs);
             Console.WriteLine(((person)obj).Name);
             Console.WriteLine(((person)obj).Age);
             Console.ReadKey();
            }
        }
    }
    [Serializable]
    class person
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }
}

  

序列化:对象序列化是将对象转换为二进制数据(字节流),反序列化是将二进制数据还原为对象。
为什么要序列化?
保持对象的持久化,将一个复杂的对象转换流,方便我们的存储与信息交换
要序列化的类型必须标记为:[Serializable]
该类型的父类也必须标记为: [Serializable]
该类型中的所有成员的类型也必须标记为: [Serializable]
序列化只会对类中的字段序列化,(只能序列化一些状态信息)
不建议使用自动属性。(每次生成的字段都可能不一样,影响反序列化)

原文地址:https://www.cnblogs.com/ZX-LMY/p/5827036.html