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

    1、BinaryFormatter二进制序列化对象实例到文件

    View Code
                FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
    
                // Construct a BinaryFormatter and use it to serialize the data to the stream.
                BinaryFormatter formatter = new BinaryFormatter();
                try
                {
                    formatter.Serialize(fs, obj);
                }
                catch (SerializationException e)
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                }
    View Code
            public static object Deserialize()
            {
                FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();
    
                    return formatter.Deserialize(fs);
                }
                catch (SerializationException e)
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                }
    
            }

     2、BinaryFormatter二级制序列化对象

    View Code
                    IFormatter formatter = new BinaryFormatter();
                    using (MemoryStream stream = new MemoryStream())
                    {
                        formatter.Serialize(stream, obj);
                        long count = stream.Length;
                        byte[] buff = stream.ToArray();
                        obj = Convert.ToBase64String(buff);
                    }
    View Code
    IFormatter fter = new BinaryFormatter();
    byte[] buff = Convert.FromBase64String(serializedObject);
    using (Stream stream = new MemoryStream(buff))
    {
        obj = fter.Deserialize(stream);
    }

    3、BinaryFormatter深拷贝

    View Code
           public static T CloneOf<T>(T serializableObject)
            {
                object objCopy = null;
    
                MemoryStream stream = new MemoryStream();
                BinaryFormatter binFormatter = new BinaryFormatter();
                binFormatter.Serialize(stream, serializableObject);
                stream.Position = 0;
                objCopy = (T)binFormatter.Deserialize(stream);
                stream.Close();
                return (T)objCopy;
            }
  • 相关阅读:
    [编译原理读书笔记][第3章 词法分析]
    [编译原理读书笔记][第2章 一个简单的语法制导程序
    [编译原理读书笔记][第一章 引论]
    [Python爬虫笔记][随意找个博客入门(一)]
    大二下学习总结
    [操作系统][简单文件系统实现]
    Hadoop综合大作业
    hive基本操作与应用
    理解MapReduce计算构架
    熟悉HBase基本操作
  • 原文地址:https://www.cnblogs.com/liyongjian/p/2840573.html
Copyright © 2011-2022 走看看