日历归档 |
|
<< < 2024 - 11 > >> | Su | Mo | Tu | We | Th | Fr | Sa | | | | | | 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 |
|
|
|
About Me |
|
|
ZhangSichu |
|
Male |
|
32 |
|
ZhangSichu@gmail.com |
|
ZhangSichu@hotmail.com |
|
ZhangSichu.com |
|
weibo.com/zhangsichu |
|
|
|
个人推荐 |
|
|
|
|
分类归档 |
|
|
|
|
My Friends |
|
|
|
|
序列化[转载]
|
一个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
//========= 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();
|
|
|
|
|
|