序列化可以以对象的形式保存数据,使数据不易被看懂。。。。。
不过序列化会带来两个不良后果,一是文件会变大,二是增加系统开销
System.Runtime.Serialization;
System.Runtime.Serialization.Formatters.Binary;
//
序列化为二进制
System.Runtime.Serialization.Formatters.Soap://序列化为soap格式的xml
IFormatters 的方法
Serialize(Stream,obj source)
Deserialize(Stream)
练习:
[
Serializable
]
//
必须先声明可被序列化,才可序列化
class
Person
{
public
string
Name;
public
int
Id;
[
NonSerialized
]
//
可以指定部分内容不序列化,则也不能被解序
public
char
Sex;
public
string
Country;
public
Person(
string
name,
int
id,
char
sex,
string
country)
{
Name = name;
Id = id;
Sex = sex;
Country = country;
}
public
override
string
ToString()
{
return
string
.Format(
"{0} {1} (&{2}) {3}"
, Name, Id, Sex, Country);
}
///
static
void
Main(
string
[] args)
{
try
{
//
填充数据,未序列化
List
<
Person
> persons =
new
List
<
Person
> { };
persons.Add(
new
Person
(
"LILI"
, 44,
'M'
,
"US"
));
persons.Add(
new
Person
(
"LUCY"
, 55,
'M'
,
"ZH"
));
persons.Add(
new
Person
(
"TIM"
, 65,
'W'
,
"JP"
));
foreach
(
Person
p
in
persons)
{
Console
.WriteLine(p);
}
//
序列化
后缀
.dat
或
.bin (
二进制
)
FileStream
saveFile =
new
FileStream
(
"persons.dat"
,
FileMode
.Create,
FileAccess
.Write);
IFormatter
serializer =
new
BinaryFormatter
();
serializer.Serialize(saveFile, persons);
saveFile.Close();
//
非托管资源手动关闭
//
读取序列化
FileStream
newFile =
new
FileStream
(
"persons.dat"
,
FileMode
.Open,
FileAccess
.Read);
List
<
Person
> newPersons = serializer.Deserialize(newFile)
as
List
<
Person
>;
newFile.Close();
foreach
(
Person
newPerson
in
newPersons)
{
Console
.WriteLine(newPersons);
}
}
结果
LILI 44 (#M) US
LUCY 55 (#M) ZH
TIM 65 (#W) JP
System.Collections.Generic.List`1[Serialize.Person]
System.Collections.Generic.List`1[Serialize.Person]
System.Collections.Generic.List`1[Serialize.Person]
LUCY 55 (#M) ZH
TIM 65 (#W) JP
System.Collections.Generic.List`1[Serialize.Person]
System.Collections.Generic.List`1[Serialize.Person]
System.Collections.Generic.List`1[Serialize.Person]