作法:將物件還原序列化How to: Deserialize an Object

當您還原序列化物件時,傳輸格式決定您會建立資料流或檔案物件。When you deserialize an object, the transport format determines whether you will create a stream or file object. 決定傳輸格式後,您可視需要呼叫 SerializeDeserialize 方法。After the transport format is determined, you can call the Serialize or Deserialize methods, as required.

還原序列化物件To deserialize an object

  1. 使用要還原序列化的物件型別,建構 XmlSerializerConstruct a XmlSerializer using the type of the object to deserialize.

  2. 呼叫 Deserialize 方法以產生物件的複本。Call the Deserialize method to produce a replica of the object. 還原序列化時,您必須先轉換原始的型別傳回的物件,如下列的範例中,(雖然它也可還原序列化從資料流),還原序列化的物件,從檔案中所示。When deserializing, you must cast the returned object to the type of the original, as shown in the following example, which deserializes the object from a file (although it could also be deserialized from a stream).

    Dim myObject As MySerializableClass  
    ' Construct an instance of the XmlSerializer with the type  
    ' of object that is being deserialized.  
    Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass))  
    ' To read the file, create a FileStream.  
    Dim myFileStream As FileStream = _  
    New FileStream("myFileName.xml", FileMode.Open)  
    ' Call the Deserialize method and cast to the object type.  
    myObject = CType( _  
    mySerializer.Deserialize(myFileStream), MySerializableClass)  
    
    MySerializableClass myObject;  
    // Construct an instance of the XmlSerializer with the type  
    // of object that is being deserialized.  
    XmlSerializer mySerializer =   
    new XmlSerializer(typeof(MySerializableClass));  
    // To read the file, create a FileStream.  
    FileStream myFileStream =   
    new FileStream("myFileName.xml", FileMode.Open);  
    // Call the Deserialize method and cast to the object type.  
    myObject = (MySerializableClass)   
    mySerializer.Deserialize(myFileStream)  
    

另請參閱See also