• C# 序列号和反序列化


    序列化是将对象在内存中的2进制数据写入到bin文件中,
    这个操作就需要引入命名空间
    using System.Runtime.Serialization.Formatters.Binary;
    以下是序列化和反序列化代码

    序列化代码:
        /// <summary> /// 保存配置文件 /// </summary> public void SaveFile() {
    首先将数据保存到作临时存储用的泛型中 manager.Temp.Clear();
    foreach (TreeNode node in this.tvSongList.Nodes) { List<SongInfo> songList = node.Tag as List<SongInfo>; Temp temp = new Temp(); temp.TreeNodeName = node.Text; temp.SongList = songList; manager.Temp.Add(temp); }
    打开文件流,创建BinaryFormatter对象
    调用BinaryFormatter对象的Serialize方法,传入两个参数(文件流对象,需要序列化的对象)
    因为序列化的时候需要用到文件流,因为使用文件流时可能出现异常,所以用try{}catch{}检测异常
    try { FileStream fs = new FileStream(@"save.bin", FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, manager); fs.Close(); } catch (Exception) { return; } }
    反序列化代码:
    创建文件流,创建BinaryFormatter对象
    调用BinaryFormatter对象的Deserialize方法,传入参数(文件流对象)
    将需要Deserialize的返回值强制转换,然后赋值给需要反序列化的对象

    因为序列化的时候需要用到文件流,因为使用文件流时可能出现异常,所以用try{}catch{}检测异常
                try
                {
                    FileStream fs = new FileStream(@"save.bin", FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();
                    this.manager = (SongManager)bf.Deserialize(fs);
                    fs.Close();
                }
                catch (Exception)
                {
                    return;
                } 
    
    
    
     
  • 相关阅读:
    C# 桥接模式(Bridge)
    C# 中介者模式(Mediator)
    C# 命令模式(Command)
    C# 模板方法(TempleteMethod)
    C# 装饰模式(Decorate)
    C# 策略模式(Strategy)
    C# 职责链模式(Chain of Responsibility)
    C# 外观模式(Facade)
    C# 单例模式(Single)
    C# 原型模式(Prototype)
  • 原文地址:https://www.cnblogs.com/BrightMoon/p/2924262.html
Copyright © 2020-2023  润新知