BinaryFormatter Klasa
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Serializuje i deserializuje obiekt lub cały graf połączonych obiektów w formacie binarnym.
public ref class BinaryFormatter sealed : System::Runtime::Serialization::IFormatter
public ref class BinaryFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
public sealed class BinaryFormatter : System.Runtime.Serialization.IFormatter
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type BinaryFormatter = class
interface IFormatter
type BinaryFormatter = class
interface IRemotingFormatter
interface IFormatter
[<System.Runtime.InteropServices.ComVisible(true)>]
type BinaryFormatter = class
interface IRemotingFormatter
interface IFormatter
Public NotInheritable Class BinaryFormatter
Implements IFormatter
Public NotInheritable Class BinaryFormatter
Implements IRemotingFormatter
- Dziedziczenie
-
BinaryFormatter
- Atrybuty
- Implementuje
Przykłady
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;
ref class App
{
public:
static 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.
// In this case we will use a file stream.
FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter^ formatter = gcnew BinaryFormatter;
try
{
formatter->Serialize( fs, addresses );
}
catch ( SerializationException^ e )
{
Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
throw;
}
finally
{
fs->Close();
}
}
static 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.dat",FileMode::Open );
try
{
BinaryFormatter^ formatter = gcnew BinaryFormatter;
// 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.
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()
{
App::Serialize();
App::Deserialize();
return 0;
}
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public 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.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
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.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// 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.
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.Formatters.Binary
Imports System.Runtime.Serialization
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.
' In this case, use a file stream.
Dim fs As New FileStream("DataFile.dat", FileMode.Create)
' Construct a BinaryFormatter and use it to serialize the data to the stream.
Dim formatter As New BinaryFormatter
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.dat", FileMode.Open)
Try
Dim formatter As New BinaryFormatter
' 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.
Dim de As DictionaryEntry
For Each de In addresses
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
Next
End Sub
End Module
Uwagi
Ostrzeżenie
BinaryFormatter
jest niezabezpieczony i nie może być zabezpieczony. Aby uzyskać więcej informacji, zobacz Przewodnik po zabezpieczeniach BinaryFormatter.
Klasy SoapFormatter i BinaryFormatter implementują IRemotingFormatter interfejs do obsługi zdalnych wywołań procedur (RPCs) i IFormatter interfejsu (dziedziczonego przez klasę IRemotingFormatter) do obsługi serializacji grafu obiektów. Klasa SoapFormatter obsługuje również elementy RPCs z obiektami ISoapMessage bez korzystania z IRemotingFormatter funkcji.
Podczas funkcji RPCs IRemotingFormatter interfejs umożliwia specyfikację dwóch oddzielnych grafów obiektów: graf obiektów do serializacji oraz dodatkowy graf zawierający tablicę obiektów nagłówka, które przekazują informacje o zdalnym wywołaniu funkcji (na przykład identyfikator transakcji lub podpis metody).
Elementy RPCs używające oddzielnej BinaryFormatter części: wywołania metody, które są wysyłane do serwera z obiektem zdalnym zawierającym metodę o nazwie i odpowiedzi metody, które są wysyłane z serwera do klienta z informacjami o stanie i odpowiedzi z wywołanej metody.
Podczas serializacji metody wywołaj pierwszy obiekt grafu obiektu musi obsługiwać IMethodCallMessage interfejs. Aby deserializować wywołanie metody, użyj Deserialize metody z parametrem HeaderHandler . Infrastruktura komunikacji zdalnie używa delegata HeaderHandler do tworzenia obiektu obsługującego ISerializable interfejs. Po BinaryFormatter wywołaniu HeaderHandler delegata zwraca identyfikator URI obiektu zdalnego z wywoływaną metodą. Pierwszy obiekt zwrócony na grafie obsługuje IMethodCallMessage interfejs.
Procedura serializacji odpowiedzi metody jest identyczna z wywołaniem metody, z wyjątkiem pierwszego obiektu grafu obiektów musi obsługiwać IMethodReturnMessage interfejs. Aby deserializować odpowiedź metody, użyj DeserializeMethodResponse metody . Aby zaoszczędzić czas, szczegóły dotyczące obiektu wywołującego nie są wysyłane do obiektu zdalnego podczas wywołania metody. Te szczegóły są zamiast tego uzyskiwane z oryginalnego wywołania metody, które jest przekazywane do DeserializeMethodResponse metody w parametrze IMethodCallMessage . Pierwszy obiekt na grafie zwrócony przez DeserializeMethodResponse metodę IMethodReturnMessage obsługuje interfejs.
Ważne
Używanie serializacji binarnej w celu deserializacji niezaufanych danych może prowadzić do zagrożeń bezpieczeństwa. Aby uzyskać więcej informacji, zobacz Weryfikowanie wszystkich danych wejściowych i przewodnik po zabezpieczeniach BinaryFormatter.
Niespłacone zastępcze
Wszelkie niezapłacone znaki zastępcze są utracone w serializacji binarnej. Na przykład następujący ciąg zawiera wysoki znak (\ud800
zastępczy Unicode ) między dwoma Test
wyrazami:
Test\ud800Test
Przed serializacji tablica bajtów ciągu jest następująca:
Wartość tablicy bajtów | Znak |
---|---|
84 | T |
101 | e |
115 | s |
116 | t |
55296 | \ud800 |
84 | T |
101 | e |
115 | s |
116 | t |
Po deserializacji wysoki znak Unicode zastępczy zostanie utracony:
Wartość tablicy bajtów | Znak |
---|---|
84 | T |
101 | e |
115 | s |
116 | t |
84 | T |
101 | e |
115 | s |
116 | t |
Konstruktory
BinaryFormatter() |
Inicjuje nowe wystąpienie klasy BinaryFormatter z domyślnymi wartościami. |
BinaryFormatter(ISurrogateSelector, StreamingContext) |
Inicjuje BinaryFormatter nowe wystąpienie klasy z danym selektorem zastępczym i kontekstem przesyłania strumieniowego. |
Właściwości
AssemblyFormat |
Pobiera lub ustawia zachowanie deserializatora w odniesieniu do znajdowania i ładowania zestawów. |
Binder |
(Niezabezpieczone) Pobiera lub ustawia obiekt typu SerializationBinder , który kontroluje powiązanie obiektu serializowanego na typ. |
Context |
Pobiera lub ustawia StreamingContext dla tego formatnika. |
FilterLevel |
Pobiera lub ustawia TypeFilterLevel automatyczne deserializacji BinaryFormatter wykonywane. |
SurrogateSelector |
Pobiera lub ustawia ISurrogateSelector obiekt, który kontroluje podstawienie typów podczas serializacji i deserializacji. |
TypeFormat |
Pobiera lub ustawia format, w którym opisy typów są określone w strumieniu serializowanym. |
Metody
Deserialize(Stream) |
Nieaktualne.
Deserializuje określony strumień do grafu obiektu. |
Deserialize(Stream, HeaderHandler) |
Deserializuje określony strumień do grafu obiektu. Podana HeaderHandler funkcja obsługuje wszystkie nagłówki w tym strumieniu. |
DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) |
Deserializuje odpowiedź na zdalne wywołanie metody z podanego Streamelementu . |
Equals(Object) |
Określa, czy dany obiekt jest taki sam, jak bieżący obiekt. (Odziedziczone po Object) |
GetHashCode() |
Służy jako domyślna funkcja skrótu. (Odziedziczone po Object) |
GetType() |
Type Pobiera wartość bieżącego wystąpienia. (Odziedziczone po Object) |
MemberwiseClone() |
Tworzy płytkią kopię bieżącego Objectelementu . (Odziedziczone po Object) |
Serialize(Stream, Object) |
Nieaktualne.
Serializuje obiekt lub graf obiektów z określonym górnym (głównym) do danego strumienia. |
Serialize(Stream, Object, Header[]) |
Serializuje obiekt lub graf obiektów z określonym górnym (głównym) do danego strumienia dołączającego podane nagłówki. |
ToString() |
Zwraca ciąg reprezentujący bieżący obiekt. (Odziedziczone po Object) |
UnsafeDeserialize(Stream, HeaderHandler) |
Deserializuje określony strumień do grafu obiektu. Podana HeaderHandler funkcja obsługuje wszystkie nagłówki w tym strumieniu. |
UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) |
Deserializuje odpowiedź na zdalne wywołanie metody z podanego Streamelementu . |