BinaryFormatter 类

以二进制格式将对象或整个连接对象图形序列化和反序列化。

**命名空间:**System.Runtime.Serialization.Formatters.Binary
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<ComVisibleAttribute(True)> _
Public NotInheritable Class BinaryFormatter
    Implements IRemotingFormatter, IFormatter
用法
Dim instance As BinaryFormatter
[ComVisibleAttribute(true)] 
public sealed class BinaryFormatter : IRemotingFormatter, IFormatter
[ComVisibleAttribute(true)] 
public ref class BinaryFormatter sealed : IRemotingFormatter, IFormatter
/** @attribute ComVisibleAttribute(true) */ 
public final class BinaryFormatter implements IRemotingFormatter, IFormatter
ComVisibleAttribute(true) 
public final class BinaryFormatter implements IRemotingFormatter, IFormatter

备注

SoapFormatterBinaryFormatter 两个类实现 IRemotingFormatter 接口以支持远程过程调用 (RPC),实现 IFormatter 接口(由 IRemotingFormatter 继承)以支持对象图形的序列化。SoapFormatter 类还支持对 ISoapMessage 对象进行 RPC,而不必使用 IRemotingFormatter 功能。

在 RPC 期间,IRemotingFormatter 接口允许指定两个独立的对象图:要序列化的对象图和一个附加图,后者包含一个传送有关远程函数调用信息(例如事务 ID 或方法签名)的标题对象数组。

使用 BinaryFormatter 的 RPC 分为两个不同的部分:方法调用,它们将发送到包含被调用方法的远程对象所在的服务器;方法响应,它们包含被调用方法的状态信息和响应信息,从服务器发送到客户端。

在方法调用的序列化过程中,对象图形的第一个对象必须支持 IMethodCallMessage 接口。若要将方法调用反序列化,请使用带有 HeaderHandler 参数的 Deserialize 方法。远程处理基础结构使用 HeaderHandler 委托来生成支持 ISerializable 接口的对象。当 BinaryFormatter 调用 HeaderHandler 委托时,它将返回包含所调用方法的远程对象的 URI。所返回图形中的第一个对象支持 IMethodCallMessage 接口。

除对象图形的第一个对象必须支持 IMethodReturnMessage 接口之外,方法响应的序列化过程与方法调用的序列化过程相同。若要将方法响应反序列化,请使用 DeserializeMethodResponse 方法。为节省时间,在方法调用期间不向远程对象发送有关调用方对象的详细信息。这些详细信息将从初始方法调用中获取,初始方法调用会传递到 IMethodCallMessage 参数中的 DeserializeMethodResponse 方法。DeserializeMethodResponse 方法返回的图形中的第一个对象支持 IMethodReturnMessage 接口。

不成对的代理项

在进行二进制序列化时将丢失所有不成对的代理项字符。例如,下面的字符串在两个 Test 单词之间包含高代理项 Unicode 字符串 (\ud800):

Test\ud800Test

在序列化之前,字符串的字节数组如下所示:

字节数组值

字符

84

T

101

e

115

s

116

t

55296

\ud800

84

T

101

e

115

s

116

t

在序列化之后,高代理项 Unicode 字符将丢失:

字节数组值

字符

84

T

101

e

115

s

116

t

84

T

101

e

115

s

116

t

示例

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
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);
        }
    }
}
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;
}
import System.*;
import System.IO.*;
import System.Collections.*;
import System.Runtime.Serialization.Formatters.Binary.*;
import System.Runtime.Serialization.*;

public class App
{
    /** @attribute STAThread()
     */
    public static void main(String[] args) throws SerializationException
    {
        Serialize();
        Deserialize();
    } //main

    static void Serialize() throws SerializationException
    {
        // 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.get_Message());
            throw e;
        }
        finally {
            fs.Close();
        }
    } //Serialize

    static void Deserialize() throws SerializationException
    {
        // 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.get_Message());
            throw e;
        }
        finally {
            fs.Close();
        }

        // To prove that the table deserialized correctly, 
        // display the key/value pairs.
        IEnumerator objEnum = addresses.GetEnumerator();
        while (objEnum.MoveNext()) {
            DictionaryEntry de = (DictionaryEntry)objEnum.get_Current();        
            Console.WriteLine("{0} lives at {1}.", de.get_Key(), 
                de.get_Value());
        }
    } //Deserialize
} //App

继承层次结构

System.Object
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows Millennium Edition、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

BinaryFormatter 成员
System.Runtime.Serialization.Formatters.Binary 命名空间