다음을 통해 공유


BinaryFormatter 클래스

개체나 연결된 개체의 전체 그래프를 이진 형식으로 serialize 및 deserialize합니다.

네임스페이스: 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(원격 프로시저 호출)를 지원하고, IRemotingFormatter에서 상속된 IFormatter 인터페이스를 구현하여 개체 그래프의 serialization을 지원합니다. 또한 SoapFormatter 클래스는 IRemotingFormatter 기능을 사용하지 않고 ISoapMessage 개체를 사용하여 RPC를 지원합니다.

RPC를 수행하는 동안 IRemotingFormatter 인터페이스를 사용하면 서로 다른 두 개체의 그래프, 즉 serialize할 개체의 그래프와 원격 함수 호출에 대한 정보(예: 트랜잭션 ID나 메서드 시그니처)를 전달할 헤더 개체의 배열이 포함된 그래프를 지정할 수 있습니다.

BinaryFormatter를 사용하는 RPC는 호출된 메서드를 포함하는 원격 개체와 함께 서버로 전송되는 메서드 호출과, 호출된 메서드의 상태 및 응답 정보와 함께 서버에서 클라이언트로 전송되는 메서드 응답으로 구분됩니다.

메서드 호출을 serialize하는 동안 개체 그래프의 첫째 개체는 IMethodCallMessage 인터페이스를 지원해야 합니다. 메서드 호출을 deserialize하려면 HeaderHandler 매개 변수와 함께 Deserialize 메서드를 사용합니다. 원격 인프라는 HeaderHandler 대리자를 사용하여 ISerializable 인터페이스를 지원하는 개체를 만듭니다. BinaryFormatter에서 HeaderHandler 대리자를 호출하면 호출되는 메서드와 함께 원격 개체의 URI가 반환됩니다. 반환되는 그래프의 첫째 개체는 IMethodCallMessage 인터페이스를 지원합니다.

메서드 응답에 대한 serialization 프로시저는 개체 그래프의 첫 번째 개체가 IMethodReturnMessage 인터페이스를 지원해야 한다는 점을 제외하고는 메서드 호출의 serialization 프로시저와 동일합니다. 메서드 응답을 deserialize하려면 DeserializeMethodResponse 메서드를 사용합니다. 시간을 절약하기 위해 메서드 호출 동안 호출자 개체에 대한 세부 사항이 원격 개체로 보내지지 않습니다. 대신 이러한 세부 사항은 IMethodCallMessage 매개 변수의 DeserializeMethodResponse 메서드에 전달되는 원래 메서드 호출에서 가져옵니다. DeserializeMethodResponse 메서드가 반환하는 그래프의 첫째 개체는 IMethodReturnMessage 인터페이스를 지원합니다.

짝이 없는 서로게이트

짝이 없는 서로게이트 문자는 이진 serialization을 수행할 때 손실됩니다. 예를 들어, 다음 문자열에서 두 단어 Test 사이에는 high surrogate 유니코드 문자(\ud800)가 들어 있습니다.

Test\ud800Test

serialization 전의 문자열 바이트 배열은 다음과 같습니다.

바이트 배열 값

문자

84

T

101

e

115

s

116

t

55296

\ud800

84

T

101

e

115

s

116

t

deserialization 후 high surrogate 유니코드 문자는 다음과 같이 손실됩니다.

바이트 배열 값

문자

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

스레드로부터의 안전성

이 형식의 모든 public static(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 네임스페이스