日期:2014-05-17  浏览次数:20384 次

c#的序列化
最近学习序列化和反序列化操作,序列化大部分网上是把类序列化了用IO存到一个文件上(比如什么的DAT,BIN后缀的),或者是序列化成XML。我在网上找到一个序列化成字节的方法可以存到数据库,但是反序列化的时候报错 Exception of type 'System.OutOfMemoryException' was thrown.
代码如下,各位大神帮帮忙
 public void SeralizeNow()
        {
            List<ClassToSeralize> listse = new List<ClassToSeralize>();
            ClassToSeralize cl1 = new ClassToSeralize();
            cl1.id = "1";
            cl1.name = "XXX";
            ClassToSeralize cl2 = new ClassToSeralize();
            cl2.id = "2";
            cl2.name = "XXXN";
            listse.Add(cl1);
            listse.Add(cl2);
            SerializeMethod(listse);
        }
        public void SerializeMethod(List<ClassToSeralize> listPers)
        {
            //序列化
            System.Runtime.Serialization.IFormatter form = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Stream st=new MemoryStream();
            form.Serialize(st,listPers);
            st.Flush();
            st.Position=0;
            byte[] bytes=new byte[st.Length];
            st.Read(bytes,0,Convert.ToInt32(st.Length));
            string s = Encoding.ASCII.GetString(bytes);
            st.Close();
            
        }
        public void DeSerializeNow(string s)
        {
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            byte[] bytes = null;
            bytes =Encoding.ASCII.GetBytes(s);
            System.IO.Stream stream = new System.IO.MemoryStream(bytes);
            List<ClassToSeralize> obj = (List<ClassToSeraliz