BinaryFormatter BinaryFormatter BinaryFormatter BinaryFormatter Class

定义

以二进制格式序列化和反序列化对象或连接对象的整个图形。Serializes and deserializes an object, or an entire graph of connected objects, in binary format.

public ref class BinaryFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type BinaryFormatter = class
    interface IRemotingFormatter
    interface IFormatter
Public NotInheritable Class BinaryFormatter
Implements IRemotingFormatter
继承
BinaryFormatterBinaryFormatterBinaryFormatterBinaryFormatter
属性
实现

示例

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

注解

SoapFormatterBinaryFormatter类将实现IRemotingFormatter接口以支持远程过程调用 (Rpc) 和IFormatter接口 (由继承IRemotingFormatter) 若要支持的对象图序列化。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. SoapFormatter类还支持使用 RpcISoapMessage对象,而无需使用IRemotingFormatter功能。The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

在 Rpc 期间,IRemotingFormatter接口允许两个单独的对象关系图的规范: 要序列化的对象图和额外的关系图,其中包含传递识别信息 (适用于远程函数调用的标头对象的数组例如,事务 ID 或方法签名)。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).

使用的 RpcBinaryFormatter分为两个不同的部分: 方法调用,这发送到与包含调用的方法的远程对象的服务器,并从服务器发送到客户端状态的方法响应和响应从调用的方法的信息。RPCs that use the BinaryFormatter separate into two distinct parts: method calls, which are sent to the server with the remote object that contains the method called, and method responses, which are sent from the server to the client with the status and response information from the called method.

在序列化的方法调用期间对象图的第一个对象必须支持IMethodCallMessage接口。During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. 若要反序列化方法调用,使用Deserialize方法替换HeaderHandler参数。To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. 远程处理基础结构使用HeaderHandler生成支持的对象的委托ISerializable接口。The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. BinaryFormatter调用HeaderHandler委托,它返回的远程对象的 URI 与被调用的方法。When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. 在图中的第一个对象返回支持IMethodCallMessage接口。The first object in the graph returned supports the IMethodCallMessage interface.

方法响应的序列化过程等同于方法调用中,除第一个对象的对象关系图必须支持IMethodReturnMessage接口。The serialization procedure for a method response is identical to that of a method call, except the first object of the object graph must support the IMethodReturnMessage interface. 若要反序列化的方法响应,使用DeserializeMethodResponse方法。To deserialize a method response, use the DeserializeMethodResponse method. 以节省时间,调用方对象有关的详细信息不会发送到远程对象方法调用期间。To save time, details about the caller object are not sent to the remote object during the method call. 这些详细信息改为来自原始方法调用,传递给DeserializeMethodResponse中的方法IMethodCallMessage参数。These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. 返回的关系图中的第一个对象DeserializeMethodResponse方法支持IMethodReturnMessage接口。The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

重要

使用二进制序列化要反序列化不受信任的数据可能会导致安全风险。Using binary serialization to deserialize untrusted data can lead to security risks. 有关详细信息,请参阅数据验证For more information, see Data Validation.

不成对的代理Unpaired Surrogates

在二进制序列化会丢失任何不成对的代理项字符。Any unpaired surrogate characters are lost in binary serialization. 例如,下面的字符串包含一个高代理项 Unicode 字符(\ud800) 在两个之间Test单词:For example, the following string contains a high surrogate Unicode character (\ud800) in between the two Test words:

Test\ud800Test

在序列化之前, 的字节数组的字符串如下所示:Before serialization, the byte array of the string is as follows:

字节数组值Byte Array Value 字符Character
8484 TT
101101 Ee
115115 s
116116 Tt
5529655296 \ud800\ud800
8484 TT
101101 Ee
115115 s
116116 Tt

反序列化之后, 的高代理项 Unicode 字符是丢失:After deserialization, the high surrogate Unicode character is lost:

字节数组值Byte Array Value 字符Character
8484 TT
101101 Ee
115115 s
116116 Tt
8484 TT
101101 Ee
115115 s
116116 Tt

构造函数

BinaryFormatter() BinaryFormatter() BinaryFormatter() BinaryFormatter()

使用默认值初始化 BinaryFormatter 类的新实例。Initializes a new instance of the BinaryFormatter class with default values.

BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext)

使用给定的代理项选择器和流上下文来初始化 BinaryFormatter 类的新实例。Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

属性

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

获取或设置与查找加集有关的反序列化器行为。Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder Binder Binder Binder

获取或设置控制将序列化对象绑定到类型的 SerializationBinder 类型的对象。Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

Context Context Context Context

获取或设置此格式化程序的 StreamingContextGets or sets the StreamingContext for this formatter.

FilterLevel FilterLevel FilterLevel FilterLevel

获取或设置 TypeFilterLevel 所执行的自动反序列化的 BinaryFormatterGets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

获取或设置控制序列化和反序列化过程的类型替换的 ISurrogateSelector.Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

TypeFormat TypeFormat TypeFormat TypeFormat

获取或设置类型说明在序列化流中的布局格式。Gets or sets the format in which type descriptions are laid out in the serialized stream.

方法

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

将指定的流反序列化为对象图形。Deserializes the specified stream into an object graph.

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

将指定的流反序列化为对象图形。Deserializes the specified stream into an object graph. 所提供的 HeaderHandler 处理该流中的任何标题。The provided HeaderHandler handles any headers in that stream.

DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。Deserializes a response to a remote method call from the provided Stream.

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

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

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

作为默认哈希函数。Serves as the default hash function.

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

获取当前实例的 TypeGets the Type of the current instance.

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

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

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

将对象或具有指定顶级(根)的对象图形序列化为给定流。Serializes the object, or graph of objects with the specified top (root), to the given stream.

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

将对象或具有指定顶级(根)的对象图形序列化为附加所提供标题的给定流。Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.

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

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler)

将指定的流反序列化为对象图形。Deserializes the specified stream into an object graph. 所提供的 HeaderHandler 处理该流中的任何标题。The provided HeaderHandler handles any headers in that stream.

UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。Deserializes a response to a remote method call from the provided Stream.

适用于