人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

May 15, 2006

序列化

Filed under: Code snippets

参考
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpguide/html/cpconBasicSerialization.asp

一个Class实现序列化需要使用SerializableAttribute() Attribute或实现ISerializable

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

!!需要特别注意的是,Serializable 属性不能被继承。如果我们从 MyObject 派生一个新类,
此新类必须也用该属性标记,否则它不能被序列化。例如,当您试图序列化下面的类的实例时,
您将获得 SerializationException。

//========= 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();

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/05/15/p21/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham