zoukankan      html  css  js  c++  java
  • 持久化一个对象

    1.对象与文件之间序列化/反序列化

           public static void SerializeToFile<T>(T obj,string dataFile)
            {
                using (FileStream fileStram = File.Create(dataFile))
                {
                    BinaryFormatter binSerializer = new BinaryFormatter();
                    binSerializer.Serialize(fileStram, obj);
                }
            }
    
            public static T DeserializeFromFile<T>(string dataFile)
            {
                T obj = default(T);
                using (FileStream fileStream = File.OpenRead(dataFile))
                {
                    BinaryFormatter binSerializer = new BinaryFormatter();
                    obj =(T)binSerializer.Deserialize(fileStream);
                }
                return obj;
            }

    测试:

           static void Main(string[] args)
            {
                ArrayList list = new ArrayList() { "Zero", "One", "Two" };
                SerializeHelper.SerializeToFile(list, "HT.data");
                ArrayList list2 = SerializeHelper.DeserializeFromFile<ArrayList>("HT.data");
                foreach (var item in list2)
                {
                    Console.WriteLine(item.ToString());
                }
    
                Console.ReadKey();
            }

    2.对象与字节流之间序列化/反序列化

            public static byte[] Serialize<T>(T obj)
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    BinaryFormatter binSerializer = new BinaryFormatter();
                    binSerializer.Serialize(memStream, obj);
                    return memStream.ToArray();
                }
            }
    
            public static T Deserialize<T>(byte[] serializedObj)
            {
                T obj = default(T);
                using (MemoryStream memStream = new MemoryStream(serializedObj))
                {
                    BinaryFormatter binSerializer = new BinaryFormatter();
                    obj = (T)binSerializer.Deserialize(memStream);
                }
                return obj;
            }
  • 相关阅读:
    三角形的个数
    Nightmare(搜索)
    Prime Ring Problem(搜索)
    Safecracker(搜索)
    丑数
    八皇后问题(回溯法)
    Dijkstra
    floyd详解
    继续畅通工程(kruskal prim)
    畅通工程
  • 原文地址:https://www.cnblogs.com/marshhu/p/7247922.html
Copyright © 2011-2022 走看看