Post

.Net序列化

一个 Class 实现序列化需要使用 SerializableAttribute() Attribute 或实现 ISerializable。缺省情况下,一个被 SerializableAttribute 标记的类型中的所有 public 和 private field(除过NonSerialized标记的field) 都会被序列化, 如果想改变序列化的处理过程, 需要实现 ISerializable 如果类型中包含 pointer, 将有可能无法从另一个环境中被反序列化,此时应该用NonSerialized标记point字段。

需要特别注意的是,Serializable 属性不能被继承。如果我们从 MyObject 派生一个新类,此新类必须也用该属性标记,否则它不能被序列化。例如,当您试图序列化下面的类的实例时,您将获得 SerializationException 参考 http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpguide/html/cpconBasicSerialization.asp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//========= A test object that needs to be serialized.
[Serializable()]
public class TestSimpleObject
{

    public int member1;
    public string member2;
    public string member3;
    public double member4;

    // A field that is not serialized.
    [NonSerialized()] public string member5;

    //=========使用
    //==Bin
    FileStream fs = new FileStream("my.bin" , FileMode.Creat);
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs , myObj);
    fs.Close();

    //==Soap
    FileStream fs = new FileStream("my_Soap.xml" , FileMode.Creat);
    SoapFormatter formatter = new SoapFormatter();
    formatter.Serialize(fs , myObj);
    fs.Close();

    //==XML
    FileStream fs = new FileStream("my.xml" , FileMode.Creat);
    System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(MyType));
    xmlSer.Serialize(fs , myObj);
    fs.Close();

    //==Deserialize
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
    MyObject obj = (MyObject) formatter.Deserialize(stream);
    stream.Close();
}
This post is licensed under CC BY 4.0 by the author.