SoapFormatter Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Serializa e desserializa um objeto, ou um grafo inteiro de objetos ligados, em formato SOAP.
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
-
SoapFormatter
- 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
Observações
Note
Esta classe está obsoleta.
Warning
BinaryFormatter é insegura e não pode ser tornada segura. Para obter mais informações, consulte o guia de segurança BinaryFormatter.
As SoapFormatter classes and BinaryFormatter implementam a IRemotingFormatter interface para suportar chamadas de procedimentos remotos (RPCs), e a IFormatter interface (herdada pelo IRemotingFormatter) para suportar a serialização de um grafo de objetos. A SoapFormatter classe também suporta RPCs com ISoapMessage objetos, sem utilizar essa IRemotingFormatter funcionalidade.
Durante os RPCs, a IRemotingFormatter interface permite a especificação de dois grafos de objeto separados: o grafo de objetos a serializar, e um grafo adicional que contém um array de objetos de cabeçalho que transmitem informação sobre a chamada de função remota (por exemplo, ID de transação ou assinatura de método). Para uma serialização adequada, o objeto raiz do primeiro grafo deve ser um objeto que implemente ou a IMethodCallMessage interface ou a IMethodReturnMessage interface.
Durante a desserialização de um RPC, é especificado um HeaderHandler delegado ao Deserialize método do formatador. A infraestrutura remota utiliza o HeaderHandler delegado para produzir um objeto que suporta a ISerializable interface. Este objeto contém a informação armazenada nos cabeçalhos e torna-se a raiz do grafo devolvido pelo desserializador.
Também SoapFormatter podem lidar com RPCs produzidos com objetos que implementam a ISoapMessage interface. Para criar um RPC sem usar a IRemotingFormatter funcionalidade, coloque um objeto que suporte a ISoapMessage interface na raiz de um grafo que está a ser serializado. Para desserializar um RPC criado desta forma, a TopObject propriedade deve ser definida para outro objeto que suporte a ISoapMessage interface e contenha a informação relevante da chamada remota.
Os objetos TimeSpan são serializados de acordo com a norma ISO 8601: 1998 secção 5.5.3.2.1 "Alternativa".
Construtores
| Name | Description |
|---|---|
| SoapFormatter() |
Inicializa uma nova instância da SoapFormatter classe com valores de propriedade por defeito. |
| SoapFormatter(ISurrogateSelector, StreamingContext) |
Inicializa uma nova instância da SoapFormatter classe com os especificados ISurrogateSelector e StreamingContext. |
Propriedades
| Name | Description |
|---|---|
| AssemblyFormat |
Obtém ou define o comportamento do desserializador no que diz respeito à localização e carregamento de assemblies. |
| Binder |
Obtém ou define o SerializationBinder que controla a ligação de um objeto serializado a um tipo. |
| Context |
Obtém ou define o StreamingContext usado com este SoapFormatter. |
| FilterLevel |
Obtém ou define o TypeFilterLevel da desserialização automática para .NET remot do Framework. |
| SurrogateSelector |
Obtém ou define o SurrogateSelector que controla a substituição de tipos durante a serialização e desserialização. |
| TopObject |
Obtém ou define o ISoapMessage no qual o objeto SOAP top é desserializado. |
| TypeFormat |
Obtém ou define o formato em que as descrições de tipo são apresentadas no fluxo serializado. |
Métodos
| Name | Description |
|---|---|
| Deserialize(Stream, HeaderHandler) |
Desserializa o fluxo num grafo de objetos, com quaisquer cabeçalhos nesse fluxo a serem tratados pelo dado HeaderHandler. |
| Deserialize(Stream) |
Desserializa os dados no fluxo fornecido e reconstitui o grafo de objetos. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Serialize(Stream, Object, Header[]) |
Serializa um objeto ou grafo de objetos com a raiz especificada ao dado Stream no formato SOAP Remote Procedure Call (RPC). |
| Serialize(Stream, Object) |
Serializa um objeto ou grafo de objetos com a raiz especificada ao dado Stream. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |