Como: desserializar um objetoHow to: Deserialize an Object

Quando você desserializar um objeto, o formato do transporte determina se você criará um fluxo ou objeto de arquivo.When you deserialize an object, the transport format determines whether you will create a stream or file object. Após o formato do transporte ser determinado, você poderá chamar os métodos Serialize ou Deserialize, conforme o necessário.After the transport format is determined, you can call the Serialize or Deserialize methods, as required.

Para desserializar um objetoTo deserialize an object

  1. Construa um XmlSerializer usando o tipo do objeto para desserializar.Construct a XmlSerializer using the type of the object to deserialize.

  2. Chame o método Deserialize para gerar uma réplica do objeto.Call the Deserialize method to produce a replica of the object. Ao desserializar, você deve converter o objeto retornado para o tipo do original, conforme mostrado no exemplo a seguir, que desserializa o objeto de um arquivo (embora também possa ser desserializado de um fluxo).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)  
    

Consulte tambémSee also