序列化

序列化


1.什么是“序列化”?

2.简单序列化实例?


1.什么是“序列化”?

http://msdn.microsoft.com/en-us/library/7ay27kt9(v=VS.71).aspx

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred.Serialization提供一种讲一个class持久化的能力。

2.简单序列化实例?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Runtime.Serialization; namespace SerializationTest { [Serializable] public class SumOf : IDeserializationCallback { private int startNumber = -1; private int endNumber; [NonSerialized] private int[] theSums; private void Serialize() { Console.WriteLine("Serializing ..."); FileStream fileStream = new FileStream("DoSum.out", FileMode.Create); BinaryFormatter binaryFomatter = new BinaryFormatter(); binaryFomatter.Serialize(fileStream, this); Console.WriteLine("...Completed"); fileStream.Close(); } public static SumOf Deserialize() { FileStream fileStream = new FileStream("DoSum.out", FileMode.Open); BinaryFormatter binaryFomatter = new BinaryFormatter(); SumOf retVal = (SumOf)binaryFomatter.Deserialize(fileStream); fileStream.Close(); return retVal; } public SumOf(int start, int end) { this.startNumber = start; this.endNumber = end; this.ComputeSums(); this.Serialize(); } private void ComputeSums() { int count = this.endNumber - this.startNumber + 1; this.theSums = new int[count]; theSums[0] = startNumber; for (int i = 1, j = startNumber + 1; i < count; ++i, ++j ) { theSums[i] = j + theSums[i - i]; } } public void DisplaySums() { foreach (int num in this.theSums) { Console.WriteLine("{0} ", num); } } public void OnDeserialization(object sender) { this.ComputeSums(); } } }

上面的代码中需要注意:

1.添加Serializable标记,显式表明该类能够序列化

2.如果类中的某个成员处于性能等考虑的话, 不想被序列化,需要标记NonSerialized

[NonSerialized] private int[] theSums;

3.如果表明某个对象不被序列化,那么在反序列化生成的对象中该属性是theSums空的。如果想要在反序列化之后重新初始化这些数据,需要实现IDeserializationCallback接口,在这里仅仅是重新计算sums。

public void OnDeserialization(object sender) { this.ComputeSums(); }


本系列的博客均是在学习过程中的个人的感悟,其中难免存在不足之处,欢迎指正,留言提出您的宝贵意见。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值