• 序列化


    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;
            }
  • 相关阅读:
    python12306抢票
    函数、迭代器、生成器、装饰器
    类(面向对象、增删改查、继承、多态、封装、反射)
    js循环、异常、函数
    js引入、注释、事件
    天融信护网面试
    Java URL处理
    Java多线程编程
    Java网络编程
    Java序列化
  • 原文地址:https://www.cnblogs.com/liyongjian/p/2840573.html
Copyright © 2020-2023  润新知