C#学习笔记(二十三):串行化和并行化
2006-04-07 16:55 努力学习的小熊 阅读(3900) 评论(3) 编辑 收藏 举报System.SerializableAttribute
串行化是指存储和获取磁盘文件、内存或其他地方中的对象。在串行化时,所有的实例数据都保存到存储介质上,在取消串行化时,对象会被还原,且不能与其原实例区别开来。
只需给类添加Serializable属性,就可以实现串行化实例的成员。
并行化是串行化的逆过程,数据从存储介质中读取出来,并赋给类的实例变量。
例:
1 [Serializable]
2 public class Person
3 {
4 public Person()
5 {
6 }
7
8 public int Age;
9 public int WeightInPounds;
10 }
2 public class Person
3 {
4 public Person()
5 {
6 }
7
8 public int Age;
9 public int WeightInPounds;
10 }
下面来看一个小例子,首先要添加命名空间
using System.Runtime.Serialization.Formatters.Binary;
下面的代码将对象Person进行序列化并存储到一个文件中
1 Person me = new Person();
2
3 me.Age = 34;
4 me.WeightInPounds = 200;
5
6 Stream s = File.Open("Me.dat",FileMode.Create);
7
8 BinaryFormatter bf = new BinaryFormatter();
9
10 bf.Serialize(s,me);
11
12 s.Close();
2
3 me.Age = 34;
4 me.WeightInPounds = 200;
5
6 Stream s = File.Open("Me.dat",FileMode.Create);
7
8 BinaryFormatter bf = new BinaryFormatter();
9
10 bf.Serialize(s,me);
11
12 s.Close();
然后再举一个并行化的例子
Stream s = File.Open("Me.dat",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
object o = bf.Deserialize(s);
Person p = o as Person;
if(p != null)
Console.WriteLine("DeSerialized Person aged:{0} whight:{1}",p.Age,p.WeightInPounds);
s.Close();
BinaryFormatter bf = new BinaryFormatter();
object o = bf.Deserialize(s);
Person p = o as Person;
if(p != null)
Console.WriteLine("DeSerialized Person aged:{0} whight:{1}",p.Age,p.WeightInPounds);
s.Close();
如果需要对部分字段序列化部分不序列化时,我们可以按照如下设置实现
[Serializable]
public class Person
{
public Person()
{
}
public int Age;
[NonSerialized]
public int WeightInPounds;
}
public class Person
{
public Person()
{
}
public int Age;
[NonSerialized]
public int WeightInPounds;
}