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";
    
        }
    
    
    }
  • 相关阅读:
    POJ 1011Sticks
    zz 深入浅出CGlib打造无入侵的类代理
    教你如何用SQL备份和还原数据库
    sql server 2008 评估期已过期解决办法
    C# 第三方分页控件的使用
    Listbox移除
    Winwos server2008 IE安全级别设置
    验证手机号码和固定电话正则表达式
    SQL 左外连接,右外连接,全连接,内连接 4种连接的区别
    SQL TOP 和 DISTINCT 结合使用
  • 原文地址:https://www.cnblogs.com/itstone/p/2535008.html
Copyright © 2011-2022 走看看