System.SerializableAttribute
串行化是指存储和获取磁盘文件、内存或其他地方中的对象。在串行化时,所有的实例数据都保存到存储介质上,在取消串行化时,对象会被还原,且不能与其原实例区别开来。
只需给类添加Serializable属性,就可以实现串行化实例的成员。
并行化是串行化的逆过程,数据从存储介质中读取出来,并赋给类的实例变量。
例:
[Serializable]2
public
class
Person3

{4
public Person()5

{6
}7

8
public int Age;9
public int WeightInPounds;10
}
下面来看一个小例子,首先要添加命名空间
using System.Runtime.Serialization.Formatters.Binary;
下面的代码将对象Person进行序列化并存储到一个文件中
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();
然后再举一个并行化的例子
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();
如果需要对部分字段序列化部分不序列化时,我们可以按照如下设置实现
[Serializable]
public
class
Person
{
public Person()
{
}
public int Age;
[NonSerialized]
public int WeightInPounds;
}
URL:http://www.cnblogs.com/Bear-Study-Hard/archive/2006/04/07/369471.html
本文介绍了如何使用 C# 进行对象的串行化和并行化操作,包括如何标记可串行化的类及选择性地串行化类成员。
909

被折叠的 条评论
为什么被折叠?



