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;
            }
  • 相关阅读:
    uva 165 Stamps
    uva 104 Bandwidth
    uva 812 Trade on Verweggistan
    Uva 1354 Mobile Computing
    uva_1422 Processor
    Codeforces Round #321 div2
    Codeforces Round #316 div2
    LightOj_1408 Batting Practice
    【共享单车】—— React后台管理系统开发手记:AntD Table高级表格
    【共享单车】—— React后台管理系统开发手记:AntD Table基础表格
  • 原文地址:https://www.cnblogs.com/liyongjian/p/2840573.html
Copyright © 2011-2022 走看看