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

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;

    namespace Sys
    {
        [Serializable] 
    //指示一个类可以序列化
        public class Element
        {
            
    //复制对象
            public object DeepClone()
            {
                
    object result = null;
                
    using (MemoryStream ms = new MemoryStream()) //内存流
                {
                    BinaryFormatter bf 
    = new BinaryFormatter();//以二进制格式序列化对象
                    bf.Serialize(ms, this);//将对象序列化为内存流
                    ms.Seek(0, SeekOrigin.Begin);
                    result 
    = bf.Deserialize(ms); //将内存流反序列化为对象
                }
                
    return result;
            }

            
    //保存对象到文件
            
    //(对象序列化到ms)→(ms写入byte[])→(byte[]写入流)
            public void WriteInstanceToFile(string fileName)
            {
                
    using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter bf 
    = new BinaryFormatter();
                    bf.Serialize(ms, 
    this);
                    ms.Seek(
    0, SeekOrigin.Begin);
                    
    byte[] buffer = new byte[ms.Length];
                    ms.Read(buffer, 
    0, buffer.Length);
                    ms.Seek(
    0, SeekOrigin.Begin);

                    FileStream stream 
    = new FileStream(fileName, FileMode.Create);
                    stream.Write(buffer,
    0,buffer.Length);
                }
            }

            
    //从文件中读取对象
            public static object ReadInstanceFromFile(string fileName)
            {
                
    object result = null;
                FileStream stream 
    = new FileStream(fileName, FileMode.Open);//以二进制格式序列化对象
                BinaryFormatter bf = new BinaryFormatter();
                result 
    = bf.Deserialize((Stream)stream); //流反序列化为对象
                stream.Close();
                
    return result;
            }
        }
    }
  • 相关阅读:
    数据仓库建模方法初步
    金融行业信用评级主题和概念清单
    数据挖掘标准规范之CRISP-DM基础
    HBase与Zookeeper数据结构查询
    R语言数据挖掘相关包总结-转帖
    R语言学习路线图-转帖
    在IIS上部署Asp.Net Core 2.2.0
    [转]Winform打包工具SetupFactory 9 的使用
    SQLite带参数处理方法
    Web.Config中配置字符串含引号的处理
  • 原文地址:https://www.cnblogs.com/perfect/p/1223777.html
Copyright © 2011-2022 走看看