C# 序列化反序列化

 

    序列化,就是格式化,是把一个对象以某种格式进行呈现。主要有三种,1、二进制序列化,2、XML序列化,3、JavaScript序列化。

     下面讲一下二进制序列化的过程

     1、在需要序列化的类的前面,标记为Serializable

     2、创建序列化的对象,就是用BinaryFormatter把我们的数据转换为二进制

     3、创建流,我们序列化的数据就是用流来进行存放的。如果是内存流,就存在内存中,如果是网络流就存在网络中。

      4、调用序列化方法

      下面是具体代码

    

/// <summary>
    /// 序列化
    /// </summary>
    class Program {
        static void Main(string[] args) {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream f = new FileStream("data", FileMode.Create, FileAccess.Write)) {
                bf.Serialize(f, new Address() { Name = "test", Id = 11 });
            }
            Console.ReadKey();
            //上面是序列化,下面是反序列化
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream f = new FileStream("data",FileMode.Open,FileAccess.Read)) {
                Console.WriteLine(bf.Deserialize(f));
            }
            //整体的全局的,游戏离开,是否保存。
            //场景,状态1,状态2, 把场景保存为二进制数据。
        }
    }

    /// <summary>
    ///  
    /// </summary>
    [Serializable]
    class Address {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    其实序列化还有一个作用就是方便程序的扩展。很多对一个集合进行解析的方式都是用序列化进行的。看如下例子

  

 这个是方式一 ,下面是序列化的方式

好像很多C#源码来对集合解析的,欢迎大家讨论。

原文地址:https://www.cnblogs.com/gdouzz/p/6086993.html