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

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.Serialization;
    //using System.Runtime.Serialization.Formatters.Binary; 
    using System.Runtime.Serialization.Formatters.Soap;    //必须加NET引用
    //.Formatter.Binary改为.Formatter.Soap;
    using System.Xml.Serialization;   
    
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace WindowsFormsApplication1
    {
       
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
    
            private void button1_Click(object sender, EventArgs e)
            { 
    
                MyObject c = new MyObject();
                FileStream fileStream = new FileStream("C:\\Users\\Stone\\Desktop\\tempxml.xml", FileMode.Create);  //对文件进行创建
               // BinaryFormatter b = new BinaryFormatter(); 
               // SoapFormatter b = new SoapFormatter();
                XmlSerializer xs = new XmlSerializer(typeof(MyObject));  //此类型必须有至少一个参数,typeof为 可序列化的对象类型 当前序列化是要对MyObject这个类进行序列化
                xs.Serialize(fileStream, c);
                fileStream.Close(); 
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            { 
    
                MyObject c = new MyObject();
                c.str = "kkkk";
                FileStream fileStream = new FileStream("C:\\Users\\Stone\\Desktop\\tempxml.xml", FileMode.Open, FileAccess.Read, FileShare.Read); //对文件打开并进行读取
                //  BinaryFormatter b = new BinaryFormatter();    //如果是要存入dat文件中 则使用BinaryFormatter 注意文件后缀名可以为任何字段,当BinaryFormatter保存的后缀为xml的时候也是可以存的进去的,但是以二进制的形式存入,不能直接查看xml文档。
              //  SoapFormatter b = new SoapFormatter();          //如果要存入xml中,则使用SoapFormatter  注意文件名后缀必须是xml,如果后缀名为txt等可读写文件时,则保存的依然是xml的格式,并非为二进制格式
                XmlSerializer xs = new XmlSerializer(typeof(MyObject)); //本类型是不想要SOAP特有的额外信息,要实现此功能也可以编写一个实现IFormatter接口的类
                c = xs.Deserialize(fileStream) as MyObject; 
                this.label1.Text = "n1:"+c.n1+"  ||  n2:"+c.n2+"  ||  str:"+c.str;
                fileStream.Close();
            }
        }
    
        [Serializable]
        public class MyObject
        {
            public int n1 = 2;
    
            public int n2 = 4;
         //   [NonSerialized]
            public String str = "xxx";
    
        }
    
    
    }
  • 相关阅读:
    设计模-设计原则-开闭原则
    使用export/import导出和导入docker容器
    Docker学习笔记(二)
    redis-cli的一些有趣也很有用的功能
    Redis命令总结
    使用domain模块捕获异步回调中的异常
    大话程序猿眼里的高并发
    使用pm2躺着实现负载均衡
    Request —— 让 Node.js http请求变得超简单
    避免uncaughtException错误引起node.js进程崩溃
  • 原文地址:https://www.cnblogs.com/itstone/p/2535008.html
Copyright © 2011-2022 走看看