c# 用binary实现序列化和反序列化
直接用实例来说明序列化和反序列化:
namespace DynamicTest
{
class Program
{
static void Main(string[] args)
{
List<Person> list = new List<Person>();
Person p = new Person();
p.ID = 1;
p.Age = 12;
p.Name = "zhiqing";
p.Money = 120.3M;
list.Add(p);
string fileName = "C:\\Users\\zhiqing\\Desktop\\test.txt";
Stream fstream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
binFormat.Serialize(fstream, list);
fstream.Close();
Console.WriteLine("c# 用二进制实现序列化");
////反序列化
try
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter binayFormat = new BinaryFormatter();
List<Person> li = (List<Person>)binayFormat.Deserialize(fs);
foreach (Person per in li)
{
Console.WriteLine("反序列化结果:ID :{0}", per.ID +","+ per.Name+"," + per.Age+"," + per.Money);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Console.WriteLine("反序列化成功");
Console.ReadLine();
}
}
}
}
运行结果: