C# Serializable
Posted 笨鹤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# Serializable相关的知识,希望对你有一定的参考价值。
System.SerializableAttribute
串行化是指存储和获取磁盘文件、内存或其他地方中的对象。在串行化时,所有的实例数据都保存到存储介质上,在取消串行化时,对象会被还原,且不能与其原实例区别开来。
只需给类添加Serializable属性,就可以实现串行化实例的成员。
并行化是串行化的逆过程,数据从存储介质中读取出来,并赋给类的实例变量。
例:
[Serializable]
2
public class Person
3
{
4
public Person()
5
{
6
}
7
8
public int Age;
9
public int WeightInPounds;
10
}
2

3

4

5

6

7

8

9

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();
2

3

4

5

6

7

8

9

10

11

12

然后再举一个并行化的例子
= 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();










如果需要对部分字段序列化部分不序列化时,我们可以按照如下设置实现










2.











































































Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1735611
以上是关于C# Serializable的主要内容,如果未能解决你的问题,请参考以下文章