zoukankan      html  css  js  c++  java
  • c# 简单序列化

    序列化:是将对象状态转换为可保持或传输的格式的过程,原因有两个,第一是想永久的保存这些数据,以便将来可以重建这些数据。第二是想把数据从一个应用程序域发送到另外一个应用程序域中去。
    反序列化:就是把存储介质中的数据重新构建为对象的一个过程。

    首先创建一个类MyObject,如以下代码

    MyObjectusing System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace SerializeTest
    {
        [Serializable]
        public class MyObject
        {
            public int n1 = 0;
            public int n2 = 0;
            public string str = null;
        }
    }

    再创建一个类用来写序列化和反序列化方法以下代码包含2种方式二进制和xml方式。

    SerializableCodeusing System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;//用二进制方式进行序列化要导入的命名空间
    using System.Xml.Serialization; //用xml方式进行序列化要导入的命名空间
    namespace SerializeTest
    {
        public class Serializable
        {
            public void SeriaByBinary()
            {
                MyObject obj = new MyObject();
                obj.n1 = 1;
                obj.n2 = 24;
                obj.str = "binary is good";
                IFormatter formatter = new BinaryFormatter();
                Stream stream=new FileStream("c:\\Myfile.bin",FileMode.Create,FileAccess.Write,FileShare.None);
                formatter.Serialize(stream,obj);
                stream.Close();
            }
            public MyObject DSeriaByBinary()
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("c:\\Myfile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
                MyObject obj=(MyObject)formatter.Deserialize(stream);
                stream.Close();
                return obj;
            }
            public void SeriaByXml()
            {
                MyObject obj = new MyObject();
                obj.n1 = 1111;
                obj.n2 = 2222;
                obj.str = "xml is great";
                XmlSerializer xmls = new XmlSerializer(typeof(MyObject));
                StreamWriter sw = new StreamWriter("c:\\myobject.xml");
                xmls.Serialize(sw,obj);
                sw.Close();
            }
            public MyObject DSeriaByXml()
            {
                XmlSerializer xmls = new XmlSerializer(typeof(MyObject));
                FileStream fs = new FileStream("c:\\myobject.xml",FileMode.Open);
                MyObject obj=(MyObject)xmls.Deserialize(fs);
                fs.Close();
                return obj;
            }
        }

    }

    最后创建TEST 窗体事件

    哈哈 ,ok 了 试试做一下吧。

  • 相关阅读:
    数组快速排序法
    javascript 的基本优化
    wdlinux mysql innodb的安装
    中文逗号替换为英文逗号 ,中英文逗号互换
    wdlinux 编译pdo_mysql
    nodejs 简单对mongodb 操作
    node.js 安装
    开启 mysql 的远程连接功能
    文件下载到本地
    webpack基础+webpack配置文件常用配置项介绍+webpack-dev-server
  • 原文地址:https://www.cnblogs.com/xiaogelove/p/1717451.html
Copyright © 2011-2022 走看看