zoukankan      html  css  js  c++  java
  • C#之序列化对象(二进制方式序列化对象)

    应用程序有时需要以对象的形式在磁盘上存储数据,FrameWork有两个可用的实现方式:

    一:System.Runtime.Serialization.Formatters.Binarry这个名称空间包含了BinarryFormatter类,它能把对象序列化为二进制数据,把二进制数据序列化为对象

    二:System.Runtime.Serialization.Formatters.Soap:这个名称空间中包含了类SoapFormat类,它能把对象序列化为Soap格式的XML数据

    以上两个类都实现了IFormatter接口,IFormatter接口提供了下面两个方法:

    BinaryFormatter序列化、反序列化对象

    [Serializable]
        class Test
        {
            public long Id;
            public string Name;
            public double Price;
    
            [NonSerialized]
            string Notes;
    
            public Test(long id, string name, double price, string notes)
            {
                this.Id = id;
                this.Name = name;
                this.Price = price;
                this.Notes = notes;
            }
    
            public override string ToString()
            {
                return string.Format("{0}:{1}  (${2:F2}) {3}", Id, Name, Price, Notes);
            }
    static void Main(string[] args)
            {
                List<Test> tests = new List<Test>();
                tests.Add(new Test(1, "苹果", 5.5, "烟台红富士"));
                tests.Add(new Test(2, "菠萝", 3.5, "海南菠萝"));
                tests.Add(new Test(3, "樱桃", 100, "智利樱桃"));
    
                //用于序列化和反序列化的对象
                IFormatter serializer = new BinaryFormatter();
    
                //开始序列化
                FileStream saveFile = new FileStream("Test.txt", FileMode.Create, FileAccess.Write);
                serializer.Serialize(saveFile, tests);
                saveFile.Close();
    
                //反序列化
                FileStream loadFile = new FileStream("Test.txt", FileMode.Open, FileAccess.Read);
                List<Test> tests2 = serializer.Deserialize(loadFile) as List<Test>;
                foreach (Test item in tests2)
                {
                    Console.WriteLine(item);
                }
                Console.ReadKey();
    
            }
  • 相关阅读:
    【前端开发】git常见使用命令行,含git提交不交叉rebase操作方法
    【前端开发】vue项目版本提交日志插件changelog
    【git可视化】git可视化工具
    【node爬虫】简单的node爬虫实例教程
    【前端开发】常见的安全攻击
    计算机网络基础知识(待补充)
    大数据生态圈的一致性
    Android Stdio部分配置
    MySQL单机上多实例安装
    MySQL Replication
  • 原文地址:https://www.cnblogs.com/lfxiao/p/6764898.html
Copyright © 2011-2022 走看看