SoapFormatter SoapFormatter SoapFormatter SoapFormatter Class

Definição

Serializa e desserializa um objeto ou um grafo inteiro de objetos conectados, em formato SOAP.Serializes and deserializes an object, or an entire graph of connected objects, in SOAP format.

public ref class SoapFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
public sealed class SoapFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type SoapFormatter = class
    interface IRemotingFormatter
    interface IFormatter
Public NotInheritable Class SoapFormatter
Implements IRemotingFormatter
Herança
SoapFormatterSoapFormatterSoapFormatterSoapFormatter
Implementações

Exemplos

#using <system.dll>
#using <system.runtime.serialization.formatters.soap.dll>

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Soap;
void Serialize()
{
   
   // Create a hashtable of values that will eventually be serialized.
   Hashtable^ addresses = gcnew Hashtable;
   addresses->Add( "Jeff", "123 Main Street, Redmond, WA 98052" );
   addresses->Add( "Fred", "987 Pine Road, Phila., PA 19116" );
   addresses->Add( "Mary", "PO Box 112233, Palo Alto, CA 94301" );
   
   // To serialize the hashtable (and its keys/values), 
   // you must first open a stream for writing.
   // We will use a file stream here.
   FileStream^ fs = gcnew FileStream( "DataFile.soap",FileMode::Create );
   
   // Construct a SoapFormatter and use it 
   // to serialize the data to the stream.
   SoapFormatter^ formatter = gcnew SoapFormatter;
   try
   {
      formatter->Serialize( fs, addresses );
   }
   catch ( SerializationException^ e ) 
   {
      Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
      throw;
   }
   finally
   {
      fs->Close();
   }

}

void Deserialize()
{
   
   // Declare the hashtable reference.
   Hashtable^ addresses = nullptr;
   
   // Open the file containing the data that we want to deserialize.
   FileStream^ fs = gcnew FileStream( "DataFile.soap",FileMode::Open );
   try
   {
      SoapFormatter^ formatter = gcnew SoapFormatter;
      
      // Deserialize the hashtable from the file and 
      // assign the reference to our local variable.
      addresses = dynamic_cast<Hashtable^>(formatter->Deserialize( fs ));
   }
   catch ( SerializationException^ e ) 
   {
      Console::WriteLine( "Failed to deserialize. Reason: {0}", e->Message );
      throw;
   }
   finally
   {
      fs->Close();
   }

   
   // To prove that the table deserialized correctly, 
   // display the keys/values to the console.
   IEnumerator^ myEnum = addresses->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DictionaryEntry^ de = safe_cast<DictionaryEntry^>(myEnum->Current);
      Console::WriteLine( " {0} lives at {1}.", de->Key, de->Value );
   }
}


[STAThread]
int main()
{
   Serialize();
   Deserialize();
}

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;

// Note: When building this code, you must reference the
// System.Runtime.Serialization.Formatters.Soap.dll assembly.
using System.Runtime.Serialization.Formatters.Soap;


class App 
{
    [STAThread]
    static void Main() 
    {
        Serialize();
        Deserialize();
    }

    static void Serialize() 
    {
        // Create a hashtable of values that will eventually be serialized.
        Hashtable addresses = new Hashtable();
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable (and its key/value pairs), 
        // you must first open a stream for writing.
        // Use a file stream here.
        FileStream fs = new FileStream("DataFile.soap", FileMode.Create);

        // Construct a SoapFormatter and use it 
        // to serialize the data to the stream.
        SoapFormatter formatter = new SoapFormatter();
        try 
        {
            formatter.Serialize(fs, addresses);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }
    }

   
    static void Deserialize() 
    {
        // Declare the hashtable reference.
        Hashtable addresses  = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.soap", FileMode.Open);
        try 
        {
            SoapFormatter formatter = new SoapFormatter();

            // Deserialize the hashtable from the file and 
            // assign the reference to the local variable.
            addresses = (Hashtable) formatter.Deserialize(fs);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }

        // To prove that the table deserialized correctly, 
        // display the key/value pairs to the console.
        foreach (DictionaryEntry de in addresses) 
        {
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
        }
    }
}
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization

' Note: When building this code, you must reference the
' System.Runtime.Serialization.Formatters.Soap.dll assembly.
Imports System.Runtime.Serialization.Formatters.Soap


Module App

   Sub Main()
      Serialize()
      Deserialize()
   End Sub

   Sub Serialize()
      ' Create a hashtable of values that will eventually be serialized.
      Dim addresses As New Hashtable
      addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052")
      addresses.Add("Fred", "987 Pine Road, Phila., PA 19116")
      addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301")

      ' To serialize the hashtable (and its key/value pairs), 
      ' you must first open a stream for writing.
      ' Use a file stream here.
      Dim fs As New FileStream("DataFile.soap", FileMode.Create)

      ' Construct a SoapFormatter and use it 
      ' to serialize the data to the stream.
      Dim formatter As New SoapFormatter
      Try
         formatter.Serialize(fs, addresses)
      Catch e As SerializationException
         Console.WriteLine("Failed to serialize. Reason: " & e.Message)
         Throw
      Finally
         fs.Close()
      End Try
   End Sub


   Sub Deserialize()
      ' Declare the hashtable reference.
      Dim addresses As Hashtable = Nothing

      ' Open the file containing the data that you want to deserialize.
      Dim fs As New FileStream("DataFile.soap", FileMode.Open)
      Try
         Dim formatter As New SoapFormatter

         ' Deserialize the hashtable from the file and 
         ' assign the reference to the local variable.
         addresses = DirectCast(formatter.Deserialize(fs), Hashtable)
      Catch e As SerializationException
         Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
         Throw
      Finally
         fs.Close()
      End Try

      ' To prove that the table deserialized correctly, 
      ' display the key/value pairs to the console.
      Dim de As DictionaryEntry
      For Each de In addresses
         Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
      Next
   End Sub
End Module

Comentários

Observação

Começando com o .NET Framework 2.0, essa classe está obsoleta.Beginning with the .NET Framework 2.0, this class is obsolete. Use BinaryFormatter em seu lugar.Use BinaryFormatter instead.

O SoapFormatter e BinaryFormatter classes implementam a IRemotingFormatter interface para oferecer suporte a chamadas de procedimento remoto (RPCs) e o IFormatter interface (herdada pelo IRemotingFormatter) para dar suporte à serialização de um gráfico de objetos.The SoapFormatter and BinaryFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface (inherited by the IRemotingFormatter) to support serialization of a graph of objects. O SoapFormatter classe também dá suporte a RPCs com ISoapMessage objetos, sem usar o IRemotingFormatter funcionalidade.The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

Durante a RPCs, o IRemotingFormatter interface permite a especificação de dois grafos de objeto separado: o grafo de objetos a serem serializados e um gráfico adicional que contém uma matriz de objetos de cabeçalho que transmitem informações sobre a chamada de função remota (para exemplo, ID da transação ou uma assinatura de método).During RPCs, the IRemotingFormatter interface allows the specification of two separate object graphs: the graph of objects to serialize, and an additional graph that contains an array of header objects that convey information about the remote function call (for example, transaction ID or a method signature). Para serialização adequada, o objeto raiz do primeiro grafo deve ser um objeto que implementa o IMethodCallMessage interface ou o IMethodReturnMessage interface.For proper serialization, the root object of the first graph must be an object that implements either the IMethodCallMessage interface or the IMethodReturnMessage interface.

Durante a desserialização de uma RPC, uma HeaderHandler delegado é especificado para o Deserialize método do formatador.During deserialization of an RPC, a HeaderHandler delegate is specified to the Deserialize method of the formatter. A infraestrutura de comunicação remota usa o HeaderHandler delegado para produzir um objeto que dá suporte a ISerializable interface.The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. Este objeto contém as informações armazenadas nos cabeçalhos e torna-se a raiz do gráfico retornado pelo desserializador.This object contains the information stored in the headers, and becomes the root of the graph returned by the deserializer.

O SoapFormatter também pode manipular RPCs são produzidos com objetos que implementam o ISoapMessage interface.The SoapFormatter can also handle RPCs that are produced with objects that implement the ISoapMessage interface. Para criar uma RPC sem usar o IRemotingFormatter funcionalidade, coloque um objeto que dá suporte ao ISoapMessage interface na raiz de um gráfico que está sendo serializado.To create an RPC without using the IRemotingFormatter functionality, place an object that supports the ISoapMessage interface at the root of a graph being serialized. Para desserializar uma RPC criada dessa maneira a TopObject propriedade deve ser definida em outro objeto que dá suporte ao ISoapMessage de interface e contém as informações relevantes de chamada remota.To deserialize an RPC created in this manner the TopObject property must be set to another object that supports the ISoapMessage interface, and contains the relevant remote call information.

Serialização de TimeSpanTimeSpan Serialization

Objetos TimeSpan são serializados de acordo com o ISO 8601: padrão de seção de 1998 5.5.3.2.1 "Alternativo".TimeSpan objects are serialized according to the ISO 8601: 1998 section 5.5.3.2.1 "Alternative" standard.

Informações de versãoVersion Information

O SoapFormatter não oferece suporte a compatibilidade de serialização entre versões do .NET Framework.The SoapFormatter does not support serialization compatibility between versions of the .NET Framework. Falha na serialização entre tipos versões 1.1 e 2.0 do Framework muitas vezes.Serialization between versions 1.1 and 2.0 types in the Framework often fails. As seguintes ações podem ser executadas para solucionar este problema:The following actions can be taken to remedy this issue:

  • Converter para usar o BinaryFormatter, que fornece a compatibilidade entre 1.1 e 2.0.Convert to use the BinaryFormatter, which provides compatibility between 1.1 and 2.0.

  • Converta os dados persistentes existentes para o novo formato.Convert existing persisted data to the new format.

  • Converta todos os produtores e consumidores de dados serializados para a versão 2.0.Convert all producers and consumers of serialized data to version 2.0.

  • Evite usar tipos alterado de 1.1 para 2.0.Avoid using types that changed from 1.1 to 2.0.

Construtores

SoapFormatter() SoapFormatter() SoapFormatter() SoapFormatter()

Inicializa uma nova instância da classe SoapFormatter com os valores da propriedade padrão.Initializes a new instance of the SoapFormatter class with default property values.

SoapFormatter(ISurrogateSelector, StreamingContext) SoapFormatter(ISurrogateSelector, StreamingContext) SoapFormatter(ISurrogateSelector, StreamingContext) SoapFormatter(ISurrogateSelector, StreamingContext)

Inicializa uma nova instância da classe SoapFormatter com o ISurrogateSelector e StreamingContext especificados.Initializes a new instance of the SoapFormatter class with the specified ISurrogateSelector and StreamingContext.

Propriedades

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

Obtém ou define o comportamento do desserializador em relação a encontrar e carregar assemblies.Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder Binder Binder Binder

Obtém ou define o SerializationBinder que controla a associação de um objeto serializado a um tipo.Gets or sets the SerializationBinder that controls the binding of a serialized object to a type.

Context Context Context Context

Obtém ou define o StreamingContext usado com este SoapFormatter.Gets or sets the StreamingContext used with this SoapFormatter.

FilterLevel FilterLevel FilterLevel FilterLevel

Obtém ou define o TypeFilterLevel de desserialização automática para comunicação remota do .NET Framework.Gets or sets the TypeFilterLevel of automatic deserialization for .NET Framework remoting.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

Obtém ou define o SurrogateSelector que controla a substituição de tipo durante a serialização e a desserialização.Gets or sets the SurrogateSelector that controls type substitution during serialization and deserialization.

TopObject TopObject TopObject TopObject

Obtém ou define o ISoapMessage no qual o objeto superior do SOAP é desserializado.Gets or sets the ISoapMessage into which the SOAP top object is deserialized.

TypeFormat TypeFormat TypeFormat TypeFormat

Obtém ou define o formato no qual as descrições de tipo são apresentadas no fluxo serializado.Gets or sets the format in which type descriptions are laid out in the serialized stream.

Métodos

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

Desserializa os dados no fluxo fornecido e reconstitui o grafo de objetos.Deserializes the data on the provided stream and reconstitutes the graph of objects.

Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler)

Desserializa o fluxo em um grafo de objeto com os cabeçalhos nesse fluxo manipulados pelo HeaderHandler especificado.Deserializes the stream into an object graph with any headers in that stream being handled by the given HeaderHandler.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object)

Serializa um objeto ou grafo de objetos com a raiz especificada para o Stream especificado.Serializes an object or graph of objects with the specified root to the given Stream.

Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[])

Serializa um objeto ou grafo de objetos com a raiz especificada para o Stream fornecido no formato RPC (Chamada de Procedimento Remoto) SOAP.Serializes an object or graph of objects with the specified root to the given Stream in the SOAP Remote Procedure Call (RPC) format.

ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)

Aplica-se a