HOW TO:序列化物件How to: Serialize an Object

若要序列化物件,首先建立要序列化的物件,並設定其公用屬性與欄位。To serialize an object, first create the object that is to be serialized and set its public properties and fields. 若要執行這項作業,您必須判斷 XML 資料流儲存 (無論是資料流或檔案) 的傳輸格式。To do this, you must determine the transport format in which the XML stream is to be stored, either as a stream or as a file. 例如,若 XML 資料流必須以永久形式儲存,請建立 FileStream 物件。For example, if the XML stream must be saved in a permanent form, create a FileStream object.


如需 XML 序列化的其他範例,請參閱 XML 序列化的範例For more examples of XML serialization, see Examples of XML Serialization.

序列化物件To serialize an object

  1. 建立物件並設定其公用欄位與屬性。Create the object and set its public fields and properties.

  2. 使用物件的型別,建構 XmlSerializerConstruct a XmlSerializer using the type of the object. 如需詳細資訊,請參閱 XmlSerializer 類別建構函式。For more information, see the XmlSerializer class constructors.

  3. 呼叫 Serialize 方法,產生 XML 資料流或物件之公用屬性與欄位的檔案表示方式。Call the Serialize method to generate either an XML stream or a file representation of the object's public properties and fields. 下列範例將建立檔案。The following example creates a file.

    Dim myObject As MySerializableClass = New MySerializableClass()  
    ' Insert code to set properties and fields of the object.  
    Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass))  
    ' To write to a file, create a StreamWriter object.  
    Dim myWriter As StreamWriter = New StreamWriter("myFileName.xml")  
    mySerializer.Serialize(myWriter, myObject)  
    MySerializableClass myObject = new MySerializableClass();  
    // Insert code to set properties and fields of the object.  
    XmlSerializer mySerializer = new   
    // To write to a file, create a StreamWriter object.  
    StreamWriter myWriter = new StreamWriter("myFileName.xml");  
    mySerializer.Serialize(myWriter, myObject);  

另請參閱See also