SerializationBinder 클래스

정의

사용자가 클래스 로딩을 제어하고 로드할 클래스를 지정할 수 있습니다.

public ref class SerializationBinder abstract
public abstract class SerializationBinder
[System.Serializable]
public abstract class SerializationBinder
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SerializationBinder
type SerializationBinder = class
[<System.Serializable>]
type SerializationBinder = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type SerializationBinder = class
Public MustInherit Class SerializationBinder
상속
SerializationBinder
특성

예제

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Reflection;
using namespace System::Security::Permissions;
ref class Version1ToVersion2DeserializationBinder;

[Serializable]
ref class Version1Type
{
public:
   Int32 x;
};


[Serializable]
ref class Version2Type: public ISerializable
{
public:
   Int32 x;
   String^ name;

   // The security attribute demands that code that calls  
   // this method have permission to perform serialization.

   [SecurityPermissionAttribute(SecurityAction::Demand,SerializationFormatter=true)]
   virtual void GetObjectData( SerializationInfo^ info, StreamingContext context )
   {
      info->AddValue( "x", x );
      info->AddValue( "name", name );
   }


private:

   // The security attribute demands that code that calls  
   // this method have permission to perform serialization.

   [SecurityPermissionAttribute(SecurityAction::Demand,SerializationFormatter=true)]
   Version2Type( SerializationInfo^ info, StreamingContext context )
   {
      x = info->GetInt32( "x" );
      try
      {
         name = info->GetString( "name" );
      }
      catch ( SerializationException^ ) 
      {
         // The 'name' field was not serialized because Version1Type 
         // did not contain this field.
         // We will set this field to a reasonable default value.
         name =  "Reasonable default value";
      }
   }
};

ref class Version1ToVersion2DeserializationBinder sealed: public SerializationBinder
{
public:
   virtual Type^ BindToType( String^ assemblyName, String^ typeName ) override
   {
      Type^ typeToDeserialize = nullptr;

      // For each assemblyName/typeName that you want to deserialize to
      // a different type, set typeToDeserialize to the desired type.
      String^ assemVer1 = Assembly::GetExecutingAssembly()->FullName;
      String^ typeVer1 =  "Version1Type";
      if ( assemblyName->Equals( assemVer1 ) && typeName->Equals( typeVer1 ) )
      {
         // To use a type from a different assembly version, 
         // change the version number using the following line of code.
         // assemblyName = assemblyName.Replace("1.0.0.0", "2.0.0.0");
         // To use a different type from the same assembly, 
         // change the type name.
         typeName =  "Version2Type";
      }

      // The following line of code returns the type.
      typeToDeserialize = Type::GetType( String::Format(  "{0}, {1}", typeName, assemblyName ) );
      return typeToDeserialize;
   }
};

ref class App
{
public:
   static void Serialize()
   {
      // To serialize the objects, you must first open a stream for writing. 
      // We will use a file stream here.
      FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
      try
      {
         // Construct a BinaryFormatter and use it 
         // to serialize the data to the stream.
         BinaryFormatter^ formatter = gcnew BinaryFormatter;

         // Construct a Version1Type Object and serialize it.
         Version1Type^ obj = gcnew Version1Type;
         obj->x = 123;
         formatter->Serialize( fs, obj );
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }
   }

   static void Deserialize()
   {
      // Declare the Version2Type reference.
      Version2Type^ obj = nullptr;

      // Open the file containing the data that we want to deserialize.
      FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Open );
      try
      {
         // Construct a BinaryFormatter and use it 
         // to deserialize the data from the stream.
         BinaryFormatter^ formatter = gcnew BinaryFormatter;

         // Construct an instance of our 
         // Version1ToVersion2TypeSerialiationBinder type.
         // This Binder type knows how to deserialize a Version1Type  
         // Object* to a Version2Type Object.
         formatter->Binder = gcnew Version1ToVersion2DeserializationBinder;
         obj = dynamic_cast<Version2Type^>(formatter->Deserialize( fs ));
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to deserialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }

      // To prove that a Version2Type Object* was deserialized, 
      // display the Object's type and fields to the console.
      Console::WriteLine( "Type of Object deserialized: {0}", obj->GetType() );
      Console::WriteLine( "x = {0}, name = {1}", obj->x, obj->name );
   }
};

[STAThread]
int main()
{
   App::Serialize();
   App::Deserialize();
   return 0;
}
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;

class App
{
    [STAThread]
    static void Main()
    {
        Serialize();
        Deserialize();
    }

    static void Serialize()
    {
        // To serialize the objects, you must first open a stream for writing.
        // Use a file stream here.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        try
        {
            // Construct a BinaryFormatter and use it
            // to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();

            // Construct a Version1Type object and serialize it.
            Version1Type obj = new Version1Type();
            obj.x = 123;
            formatter.Serialize(fs, obj);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }

    static void Deserialize()
    {
        // Declare the Version2Type reference.
        Version2Type obj = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try
        {
            // Construct a BinaryFormatter and use it
            // to deserialize the data from the stream.
            BinaryFormatter formatter = new BinaryFormatter();

            // Construct an instance of our the
            // Version1ToVersion2TypeSerialiationBinder type.
            // This Binder type can deserialize a Version1Type
            // object to a Version2Type object.
            formatter.Binder = new Version1ToVersion2DeserializationBinder();

            obj = (Version2Type) formatter.Deserialize(fs);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }

        // To prove that a Version2Type object was deserialized,
        // display the object's type and fields to the console.
        Console.WriteLine("Type of object deserialized: " + obj.GetType());
        Console.WriteLine("x = {0}, name = {1}", obj.x, obj.name);
    }
}

[Serializable]
class Version1Type
{
    public Int32 x;
}

[Serializable]
class Version2Type : ISerializable
{
    public Int32 x;
    public String name;

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("x", x);
        info.AddValue("name", name);
    }

    private Version2Type(SerializationInfo info, StreamingContext context)
    {
        x = info.GetInt32("x");
        try
        {
            name = info.GetString("name");
        }
        catch (SerializationException)
        {
            // The "name" field was not serialized because Version1Type
            // did not contain this field.
            // Set this field to a reasonable default value.
            name = "Reasonable default value";
        }
    }
}

sealed class Version1ToVersion2DeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        Type typeToDeserialize = null;

        // For each assemblyName/typeName that you want to deserialize to
        // a different type, set typeToDeserialize to the desired type.
        String assemVer1 = Assembly.GetExecutingAssembly().FullName;
        String typeVer1 = "Version1Type";

        if (assemblyName == assemVer1 && typeName == typeVer1)
        {
            // To use a type from a different assembly version,
            // change the version number.
            // To do this, uncomment the following line of code.
            // assemblyName = assemblyName.Replace("1.0.0.0", "2.0.0.0");

            // To use a different type from the same assembly,
            // change the type name.
            typeName = "Version2Type";
        }

        // The following line of code returns the type.
        typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
            typeName, assemblyName));

        return typeToDeserialize;
    }
}
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Reflection
Imports System.Security.Permissions

Class App
   <STAThread()> Shared Sub Main()
      Serialize()
      Deserialize()
   End Sub


   Shared Sub Serialize()
      ' To serialize the objects, you must first open a stream for writing. 
      ' Use a file stream here.
      Dim fs As New FileStream("DataFile.dat", FileMode.Create)

      Try
         ' Construct a BinaryFormatter and use it 
         ' to serialize the data to the stream.
         Dim formatter As New BinaryFormatter

         ' Construct a Version1Type object and serialize it.
         Dim obj As New Version1Type
         obj.x = 123
         formatter.Serialize(fs, obj)
      Catch e As SerializationException
         Console.WriteLine("Failed to serialize. Reason: " & e.Message)
         Throw
      Finally
         fs.Close()
      End Try
   End Sub


   Shared Sub Deserialize()
      ' Declare the Version2Type reference.
      Dim obj As Version2Type = Nothing

      ' Open the file containing the data that you want to deserialize.
      Dim fs As New FileStream("DataFile.dat", FileMode.Open)
      Try
         ' Construct a BinaryFormatter and use it 
         ' to deserialize the data from the stream.
         Dim formatter As New BinaryFormatter

         ' Construct an instance of the 
         ' Version1ToVersion2TypeSerialiationBinder type.
         ' This Binder type can deserialize a Version1Type  
         ' object to a Version2Type object.
         formatter.Binder = New Version1ToVersion2DeserializationBinder

         obj = DirectCast(formatter.Deserialize(fs), Version2Type)
      Catch e As SerializationException
         Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
         Throw
      Finally
         fs.Close()
      End Try

      ' To prove that a Version2Type object was deserialized, 
      ' display the object's type and fields to the console.
      Console.WriteLine("Type of object deserialized: {0}", obj.GetType())
      Console.WriteLine("x = {0}, name = {1}", obj.x, obj.name)
   End Sub
End Class


<Serializable()> Class Version1Type
   Public x As Int32
End Class


<Serializable()> Class Version2Type
   Implements ISerializable
   Public x As Int32
   Public name As String

   ' The security attribute demands that code that calls  
   ' this method have permission to perform serialization.
   <SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter:=True)> _
   Private Sub GetObjectData(ByVal info As SerializationInfo, _
         ByVal context As StreamingContext) Implements ISerializable.GetObjectData
      info.AddValue("x", x)
      info.AddValue("name", name)
   End Sub

   ' The security attribute demands that code that calls  
   ' this method have permission to perform serialization.
   <SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter:=True)> _
   Private Sub New(ByVal info As SerializationInfo, _
         ByVal context As StreamingContext)
      x = info.GetInt32("x")
      Try
         name = info.GetString("name")
      Catch e As SerializationException
         ' The "name" field was not serialized because 
         ' Version1Type did not contain this field.
         ' Set this field to a reasonable default value.
         name = "Reasonable default value"
      End Try
   End Sub
End Class


NotInheritable Class Version1ToVersion2DeserializationBinder
   Inherits SerializationBinder
   Public Overrides Function BindToType(ByVal assemblyName As String, _
         ByVal typeName As String) As Type

      Dim typeToDeserialize As Type = Nothing

      ' For each assemblyName/typeName that you want to deserialize
      ' to a different type, set typeToDeserialize to the desired type.
      Dim assemVer1 As String = [Assembly].GetExecutingAssembly().FullName
      Dim typeVer1 As String = GetType(Version1Type).FullName

      If assemblyName = assemVer1 And typeName = typeVer1 Then
         ' To use a type from a different assembly version, 
         ' change the version number.
         ' To do this, uncomment the following code.
         ' assemblyName = assemblyName.Replace("1.0.0.0", "2.0.0.0")

         ' To use a different type from the same assembly, 
         ' change the type name.
         typeName = typeName.Replace("Version1Type", "Version2Type")
      End If

      ' The following code returns the type.
      typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, _
                                       assemblyName))

      Return typeToDeserialize
   End Function
End Class

설명

안전하지 않은 직렬 변환기

경고

BinaryFormatter 는 안전 하지 않으며 안전 하 게 만들 수 없습니다. 자세한 내용은 Binaryformatter 보안 가이드를 참조 하세요.

serialization 도중에, 포맷터는 올바른 형식 및 버전의 개체 인스턴스를 만드는 데 필요한 정보를 전송합니다. 이 정보에는 일반적으로 개체에 대한 어셈블리 이름 및 전체 형식 이름이 포함됩니다. 어셈블리 이름에는 어셈블리의 이름, 버전 및 강력한 이름( 강력한 이름의 어셈블리 참조) 해시가 포함됩니다. 기본적으로, deserialization은 이 정보를 사용하여 동일한 개체의 인스턴스를 만듭니다. 보안 정책에 의해 제한되는 어셈블리 로딩은 예외입니다. 클래스가 어셈블리 간에 이동하거나 서버와 클라이언트에서 서로 다른 버전의 클래스를 필요로 하므로 일부 사용자는 로드할 클래스를 제어해야 합니다.

SerializationBinder 보안에 사용할 수 없습니다. 신뢰할 수 없는 원본에서 일부 데이터를 역직렬화하려고 할 때 몇 가지 보안 악용이 있을 수 있습니다. 바인더는 애플리케이션 도메인에 로드되는 형식을 검사할 수 있는 기회를 제공하지만 악용이 가능하지 않다는 보장은 없습니다. 자세한 내용은 BinaryFormatter 보안 가이드를 참조하세요. 그런 다음 거부된 형식 목록 또는 허용되는 형식 목록을 유지 관리하고 로드 및 인스턴스화되는 형식을 제한할 수 있습니다. 또한 어떤 정보가 전선에 배치되는지 염두에 두어야 합니다. 네트워크에서 형식 이름 또는 기타 데이터를 보낼 때 전송 또는 메시지 보안을 사용할 수 있습니다.

경고

직렬화되는 정보를 완전히 확신하는 경우에만 사용합니다 SerializationBinder . 악의적인 유형으로 인해 예기치 않은 동작이 발생할 수 있습니다.

이 클래스는 추상 기본 클래스입니다. 모든 바인더는 이 클래스를 확장합니다.

구현자 참고

SerializationBinder에서 상속하는 경우 BindToType(String, String) 멤버를 재정의해야 합니다.

생성자

SerializationBinder()

SerializationBinder 클래스의 새 인스턴스를 초기화합니다.

메서드

BindToName(Type, String, String)

파생 클래스에서 재정의된 경우 형식으로 직렬화된 개체의 바인딩을 제어합니다.

BindToType(String, String)

파생 클래스에서 재정의된 경우 형식으로 직렬화된 개체의 바인딩을 제어합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보