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; }
[Serializable] public class Book { string name; float price; string author; public Book(string bookname, float bookprice, string bookauthor) { name = bookname; price = bookprice; author = bookauthor; } }
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 }
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;
}
public class Book
{
string name;
float price;
string author; public Book(string bookname, float bookprice, string bookauthor)
{
name = bookname;
price = bookprice;
author = bookauthor;
}
}
{
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
}