zoukankan      html  css  js  c++  java
  • 序列化反序列化

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace 序列化反序列化
    {
    class Program
    {
    static void Main(string[] args)
    {
    //需要将对象的状态保存起来 持久化
    //序列化:将对象的状态持久化到某种设备上(磁盘)
    //要将类标记为Serializable 这个类的对象才能被序列化
    //以二进制的方式进行序列化,而不是文本文档

    //反序列化:将之前序列化的文件还原为对象
    #region[序列化]
    Person p1 = new Person() { Age = 19, Name = "Rose" };
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    using (FileStream fs = new FileStream("se.bin", FileMode.Create))
    {
    bf.Serialize(fs, p1);
    }
    #endregion

    #region【反序列化】
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf2 = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    using (FileStream fs = new FileStream("se.bin", FileMode.Open))
    {
    object obj = bf2.Deserialize(fs);
    Person p3 = obj as Person;
    Console.WriteLine("Age:" + p3.Age.ToString() + "Name:" + p3.Name);
    }
    #endregion


    #region [将一个对象保存到文件文本中,用文件的方式让对象持久化,但是麻烦]
    Person p = new Person();
    if (File.Exists(@"1.txt"))
    {
    string[] strlines = File.ReadAllLines(@"1.txt");
    p.Age = int.Parse(strlines[0]);
    p.Name = strlines[1];
    }
    else
    {
    p.Age = 19;
    p.Name = "Jack";
    File.WriteAllLines(@"1.txt", new string[] { p.Age.ToString(), p.Name });
    }
    #endregion
    Console.Read();
    }

    }
    [Serializable]//表示这个对象可以被序列化,里面的成员如果有其它类,那么这个类也应该需要标记Serializable
    public class Person
    {
    public int Age { get; set; }
    public string Name { get; set; }
    }
    }

  • 相关阅读:
    Vue 插件写法
    js创建对象的多种方式及优缺点
    webpack原理与实战
    发布高性能迷你React框架anu
    Windows 同一时候开启核心显卡与独立显卡(不接显示器启动核芯显卡)
    基于QT和OpenCV的人脸检測识别系统(1)
    Cocos2d-x中背景音乐播放暂停与继续
    使用Xcode和Instruments调试解决iOS内存泄露
    Shell 命令行快捷键
    ExtJS学习-----------Ext.Array,ExtJS对javascript中的Array的扩展(实例)
  • 原文地址:https://www.cnblogs.com/sumg/p/3743982.html
Copyright © 2011-2022 走看看