ISerializable 인터페이스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
개체가 이진 및 XML serialization을 통해 자체 직렬화 및 역직렬화를 제어할 수 있습니다.
public interface class ISerializable
public interface ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable
type ISerializable = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type ISerializable = interface
Public Interface ISerializable
- 파생
- 특성
예제
다음 코드 예제에서는 인터페이스를 사용하여 클래스에 ISerializable 대한 사용자 지정 이진 serialization 동작을 정의하는 방법을 보여 줍니다.
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 SingletonSerializationHelper;
// There should be only one instance of this type per AppDomain.
[Serializable]
public ref class Singleton sealed: public ISerializable
{
private:
// This is the one instance of this type.
static Singleton^ theOneObject = gcnew Singleton;
public:
// Here are the instance fields.
String^ someString;
Int32 someNumber;
private:
// Private constructor allowing this type to construct the singleton.
Singleton()
{
// Do whatever is necessary to initialize the singleton.
someString = "This is a String* field";
someNumber = 123;
}
public:
// A method returning a reference to the singleton.
static Singleton^ GetSingleton()
{
return theOneObject;
}
// A method called when serializing a Singleton.
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::LinkDemand,
Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
virtual void GetObjectData( SerializationInfo^ info, StreamingContext context )
{
// Instead of serializing this Object*, we will
// serialize a SingletonSerializationHelp instead.
info->SetType( SingletonSerializationHelper::typeid );
// No other values need to be added.
}
// NOTE: ISerializable*'s special constructor is NOT necessary
// because it's never called
};
[Serializable]
private ref class SingletonSerializationHelper sealed: public IObjectReference
{
public:
// This Object* has no fields (although it could).
// GetRealObject is called after this Object* is deserialized
virtual Object^ GetRealObject( StreamingContext context )
{
// When deserialiing this Object*, return a reference to
// the singleton Object* instead.
return Singleton::GetSingleton();
}
};
[STAThread]
int main()
{
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;
// Create an array with multiple elements refering to
// the one Singleton Object*.
array<Singleton^>^a1 = {Singleton::GetSingleton(),Singleton::GetSingleton()};
// This displays S"True".
Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a1[ 0 ] == a1[ 1 ]) );
// Serialize the array elements.
formatter->Serialize( fs, a1 );
// Deserialize the array elements.
fs->Position = 0;
array<Singleton^>^a2 = (array<Singleton^>^)formatter->Deserialize( fs );
// This displays S"True".
Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a2[ 0 ] == a2[ 1 ]) );
// This displays S"True".
Console::WriteLine( "Do all array elements refer to the same Object? {0}", (a1[ 0 ] == a2[ 0 ]) );
}
catch ( SerializationException^ e )
{
Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
throw;
}
finally
{
fs->Close();
}
return 0;
}
using System;
using System.Text;
using System.IO;
// Add references to Soap and Binary formatters.
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap ;
using System.Runtime.Serialization;
[Serializable]
public class MyItemType : ISerializable
{
public MyItemType()
{
// Empty constructor required to compile.
}
// The value to serialize.
private string myProperty_value;
public string MyProperty
{
get { return myProperty_value; }
set { myProperty_value = value; }
}
// Implement this method to serialize data. The method is called
// on serialization.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("props", myProperty_value, typeof(string));
}
// The special constructor is used to deserialize values.
public MyItemType(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
myProperty_value = (string) info.GetValue("props", typeof(string));
}
}
// This is a console application.
public static class Test
{
static void Main()
{
// This is the name of the file holding the data. You can use any file extension you like.
string fileName = "dataStuff.myData";
// Use a BinaryFormatter or SoapFormatter.
IFormatter formatter = new BinaryFormatter();
//IFormatter formatter = new SoapFormatter();
Test.SerializeItem(fileName, formatter); // Serialize an instance of the class.
Test.DeserializeItem(fileName, formatter); // Deserialize the instance.
Console.WriteLine("Done");
Console.ReadLine();
}
public static void SerializeItem(string fileName, IFormatter formatter)
{
// Create an instance of the type and serialize it.
MyItemType t = new MyItemType();
t.MyProperty = "Hello World";
FileStream s = new FileStream(fileName , FileMode.Create);
formatter.Serialize(s, t);
s.Close();
}
public static void DeserializeItem(string fileName, IFormatter formatter)
{
FileStream s = new FileStream(fileName, FileMode.Open);
MyItemType t = (MyItemType)formatter.Deserialize(s);
Console.WriteLine(t.MyProperty);
}
}
Imports System.Text
Imports System.IO
' Add references to Soap and Binary formatters.
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Runtime.Serialization
<Serializable()> _
Public Class MyItemType
Implements ISerializable
' Empty constructor required to compile.
Public Sub New()
End Sub
' The value to serialize.
Private myProperty_value As String
Public Property MyProperty() As String
Get
Return myProperty_value
End Get
Set(value As String)
myProperty_value = value
End Set
End Property
' Implement this method to serialize data. The method is called
' on serialization.
Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
' Use the AddValue method to specify serialized values.
info.AddValue("props", myProperty_value, GetType(String))
End Sub
' The special constructor is used to deserialize values.
Public Sub New(info As SerializationInfo, context As StreamingContext)
' Reset the property value using the GetValue method.
myProperty_value = DirectCast(info.GetValue("props", GetType(String)), String)
End Sub
End Class
' This is a console application.
Public Class Test
Public Shared Sub Main()
' This is the name of the file holding the data. You can use any file extension you like.
Dim fileName As String = "dataStuff.myData"
' Use a BinaryFormatter or SoapFormatter.
Dim formatter As IFormatter = New BinaryFormatter()
' Dim formatter As IFormatter = New SoapFormatter()
Test.SerializeItem(fileName, formatter)
' Serialize an instance of the class.
Test.DeserializeItem(fileName, formatter)
' Deserialize the instance.
Console.WriteLine("Done")
Console.ReadLine()
End Sub
Public Shared Sub SerializeItem(fileName As String, formatter As IFormatter)
' Create an instance of the type and serialize it.
Dim myType As New MyItemType()
myType.MyProperty = "Hello World"
Dim fs As New FileStream(fileName, FileMode.Create)
formatter.Serialize(fs, myType)
fs.Close()
End Sub
Public Shared Sub DeserializeItem(fileName As String, formatter As IFormatter)
Dim fs As New FileStream(fileName, FileMode.Open)
Dim myType As MyItemType = DirectCast(formatter.Deserialize(fs), MyItemType)
Console.WriteLine(myType.MyProperty)
End Sub
End Class
설명
이진 또는 XML serialization을 사용하여 serialize할 수 있는 모든 클래스는 로 SerializableAttribute표시되어야 합니다. 클래스가 이진 또는 XML serialization 프로세스를 제어해야 하는 경우 인터페이스를 구현할 ISerializable 수 있습니다. 는 Formatter serialization 시 를 GetObjectData 호출하고 제공된 SerializationInfo 를 개체를 나타내는 데 필요한 모든 데이터로 채웁니다. 는 Formatter 그래프에 개체의 형식을 사용하여 을 만듭니다 SerializationInfo . 프록시를 직접 보내야 하는 개체는 및 AssemblyName 메서드를 FullTypeNameSerializationInfo 사용하여 전송된 정보를 변경할 수 있습니다.
클래스 상속의 경우 를 구현하는 기본 클래스에서 파생되는 클래스를 serialize할 수 있습니다.ISerializable 이 경우 파생 클래스는 의 구현 GetObjectData내에서 의 GetObjectData 기본 클래스 구현을 호출해야 합니다. 그렇지 않으면 기본 클래스의 데이터가 serialize되지 않습니다.
인터페이스는 ISerializable 서명 constructor (SerializationInfo information, StreamingContext context)
이 인 생성자를 의미합니다. 역직렬화 시 현재 생성자는 의 데이터가 포맷터에 SerializationInfo 의해 역직렬화된 후에만 호출됩니다. 일반적으로 클래스가 이 아닌 sealed
경우 이 생성자는 이어야 합니다protected
.
개체가 역직렬화되는 순서는 보장할 수 없습니다. 예를 들어 한 형식이 아직 역직렬화되지 않은 형식을 참조하는 경우 예외가 발생합니다. 이러한 종속성이 있는 형식을 만드는 경우 인터페이스 및 OnDeserialization
메서드를 구현하여 IDeserializationCallback
문제를 해결할 수 있습니다.
serialization 아키텍처는 를 확장하는 Object형식과 동일하게 확장 MarshalByRefObject 되는 개체 형식을 처리합니다. 이러한 형식은 로 SerializableAttribute 표시하고 인터페이스를 ISerializable 다른 개체 형식으로 구현할 수 있습니다. 해당 개체 상태는 캡처되어 스트림에 유지됩니다.
이러한 형식이 를 통해 System.Runtime.Remoting사용되는 경우 원격 인프라는 일반적인 serialization을 선점하고 대신 프록시를 로 직렬화하는 서로게이트를 MarshalByRefObject제공합니다. 서로게이트는 특정 형식의 개체를 직렬화하고 역직렬화하는 방법을 알고 있는 도우미입니다. 대부분의 경우 사용자에게 보이지 않는 프록시는 형식 ObjRef입니다.
일반적인 디자인 패턴으로 클래스가 직렬화 가능한 특성으로 표시되고 를 확장하는 MarshalByRefObject것은 드문 일입니다. 개발자는 이러한 두 특성을 결합할 때 가능한 직렬화 및 원격 시나리오에 대해 신중하게 생각해야 합니다. 이를 적용할 수 있는 한 가지 예는 를 사용하는 MemoryStream것입니다. ()의 MemoryStream 기본 클래스는 에서 MarshalByRefObject확장되지만 의 MemoryStream 상태를 캡처하고 의지에 따라 복원할 수Stream 있습니다. 따라서 이 스트림의 상태를 데이터베이스로 직렬화하고 나중에 복원하는 것이 의미가 있을 수 있습니다. 그러나 원격을 통해 사용하면 이 형식의 개체가 프록시됩니다.
를 확장하는 MarshalByRefObject클래스의 serialization에 대한 자세한 내용은 를 참조하세요 RemotingSurrogateSelector. 구현에 대한 자세한 내용은 사용자 지정 Serialization을 ISerializable참조하세요.
참고
이 인터페이스는 를 사용하는 JSON serialization에는 System.Text.Json적용되지 않습니다.
구현자 참고
개체가 자체 직렬화 및 역직렬화에 참여할 수 있도록 이 인터페이스를 구현합니다.
메서드
GetObjectData(SerializationInfo, StreamingContext) |
대상 개체를 직렬화하는 데 필요한 데이터로 SerializationInfo를 채웁니다. |