您的位置:首页 > 编程语言 > C#

C#之序列化对象(二进制方式序列化对象)

2017-04-25 22:06 253 查看

应用程序有时需要以对象的形式在磁盘上存储数据,FrameWork有两个可用的实现方式:

一:System.Runtime.Serialization.Formatters.Binarry这个名称空间包含了BinarryFormatter类,它能把对象序列化为二进制数据,把二进制数据序列化为对象

二:System.Runtime.Serialization.Formatters.Soap:这个名称空间中包含了类SoapFormat类,它能把对象序列化为Soap格式的XML数据

以上两个类都实现了IFormatter接口,IFormatter接口提供了下面两个方法:

BinaryFormatter序列化、反序列化对象

[Serializable]
class Test
{
public long Id;
public string Name;
public double Price;

[NonSerialized]
string Notes;

public Test(long id, string name, double price, string notes)
{
this.Id = id;
this.Name = name;
this.Price = price;
this.Notes = notes;
}

public override string ToString()
{
return string.Format("{0}:{1}  (${2:F2}) {3}", Id, Name, Price, Notes);
}
static void Main(string[] args)
{
List<Test> tests = new List<Test>();
tests.Add(new Test(1, "苹果", 5.5, "烟台红富士"));
tests.Add(new Test(2, "菠萝", 3.5, "海南菠萝"));
tests.Add(new Test(3, "樱桃", 100, "智利樱桃"));

//用于序列化和反序列化的对象
IFormatter serializer = new BinaryFormatter();

//开始序列化
FileStream saveFile = new FileStream("Test.txt", FileMode.Create, FileAccess.Write);
serializer.Serialize(saveFile, tests);
saveFile.Close();

//反序列化
FileStream loadFile = new FileStream("Test.txt", FileMode.Open, FileAccess.Read);
List<Test> tests2 = serializer.Deserialize(loadFile) as List<Test>;
foreach (Test item in tests2)
{
Console.WriteLine(item);
}
Console.ReadKey();

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: