序列化一个类?
这个类里有ArrayList的数据成员。
那么是直接序列化这个类的对象还是序列化对象里的数据成员arrayList?

解决方案 »

  1.   

    XmlSerializer
    BinaryFormatter都可以序列化
     [Serializable] 
    public static byte[] Serialize(object obj)
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                bf.Serialize(stream, obj);
                byte[] datas = stream.ToArray();
                stream.Dispose();
                return datas;
            }
      

  2.   

    [Serializable]
    public class Book
    {
        string name;
        float      price;
        string author;    public Book(string bookname, float bookprice, string bookauthor)
        {
         name = bookname;
         price = bookprice;
         author = bookauthor;
        }
    }
      

  3.   

        static void Main(string[] args)
        {
         Book book = new Book("Day and Night", 30.0f, "Bruce");     using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create))
         {
          BinaryFormatter formatter = new BinaryFormatter();
          formatter.Serialize(fs, book);
         }     book = null;     using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Open))
         {
          BinaryFormatter formatter = new BinaryFormatter();
          book = (Book)formatter.Deserialize(fs);//在这里大家要注意咯,他的返回值是object
         }