ISerializable.GetObjectData(SerializationInfo, StreamingContext) 메서드


대상 개체를 직렬화하는 데 필요한 데이터로 SerializationInfo를 채웁니다.Populates a SerializationInfo with the data needed to serialize the target object.

 void GetObjectData(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
public void GetObjectData (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
abstract member GetObjectData : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> unit
Public Sub GetObjectData (info As SerializationInfo, context As StreamingContext)

매개 변수


데이터로 채울 SerializationInfo입니다.The SerializationInfo to populate with data.


이 serialization에 대한 대상입니다(StreamingContext 참조).The destination (see StreamingContext) for this serialization.



호출자에게 필요한 권한이 없는 경우The caller does not have the required permission.


다음 예제에서는 GetObjectData 메서드를 사용 하 여 serialize 된 개체에 대 한 대체 값을 설정 합니다.The following example uses the GetObjectData method to set alternate values for a serialized object. 이 코드는 SerializationInfo 클래스의 AddValue 메서드를 사용 하 여 개체가 serialize 될 때 대체 값을 저장 합니다.The code uses the AddValue method of the SerializationInfo class to store the alternate values when the object is serialized. 반대로 deserialization 중에 Person 클래스의 생성자가 호출 되 면 GetValue 메서드를 사용 하 여 alternatve 값을 검색 하 고 개체의 필드에 다시 할당 합니다.Conversely, when the constructor of the Person class is called during deserialization, the alternatve values are retrieved using the GetValue method and reassigned to the object's fields.

using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.IO;

[assembly: SecurityPermission(
SecurityAction.RequestMinimum, Execution = true)]
namespace ISerializableExample
    class Program
        public static void Main()
            catch (Exception exc)
                Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace);
                Console.WriteLine("Press Enter to exit....");

        static void Run()
            BinaryFormatter binaryFmt = new BinaryFormatter();
            Person p = new Person();
            p.IdNumber = 1010;
            p.Name = "AAAAA";
            FileStream fs = new FileStream
                ("Person.xml", FileMode.OpenOrCreate);
            binaryFmt.Serialize(fs, p);
                ("Original Name: {0}, Original ID: {1}", p.Name, p.IdNumber);

            // Deserialize.
            fs = new FileStream
                ("Person.xml", FileMode.OpenOrCreate);
            Person p2 = (Person)binaryFmt.Deserialize(fs);
                Console.WriteLine("New Name: {0}, New ID: {1}", p2.Name, p2.IdNumber);
    public class Person : ISerializable
        private string name_value;
        private int ID_value;

        public Person() { }
        protected Person(SerializationInfo info, StreamingContext context)
            if (info == null)
                throw new System.ArgumentNullException("info");
            name_value = (string)info.GetValue("AltName", typeof(string));
            ID_value = (int)info.GetValue("AltID", typeof(int));

            Flags = SecurityPermissionFlag.SerializationFormatter)]
        public virtual void GetObjectData(
        SerializationInfo info, StreamingContext context)
            if (info == null)
                throw new System.ArgumentNullException("info");
            info.AddValue("AltName", "XXX");
            info.AddValue("AltID", 9999);

        public string Name
            get { return name_value; }
            set { name_value = value; }

        public int IdNumber
            get { return ID_value; }
            set { ID_value = value; }
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Security.Permissions
Imports System.IO

<Assembly: SecurityPermission _
(SecurityAction.RequestMinimum, Execution:=True)> 

Class Program

    Public Shared Sub Main()
        Catch exc As Exception
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace)
            Console.WriteLine("Press Enter to exit....")
        End Try

    End Sub

    Shared Sub Run()
        Dim binaryFmt As New BinaryFormatter()
        Dim p As New Person()
        p.IdNumber = 1010
        p.Name = "AAAAA"
        Dim fs As New FileStream("Person.xml", FileMode.OpenOrCreate)
        binaryFmt.Serialize(fs, p)
        Console.WriteLine _
        ("Original Name: {0}, Original ID: {1}", p.Name, p.IdNumber)

        ' Deserialize.
        fs = New FileStream("Person.xml", FileMode.OpenOrCreate)
        Dim p2 As Person = CType(binaryFmt.Deserialize(fs), Person)
        Console.WriteLine("New Name: {0}, New ID: {1}", _
        p2.Name, p2.IdNumber)
    End Sub
End Class

<Serializable()> _
Public Class Person
    Implements ISerializable
    Private name_value As String
    Private ID_value As Integer

    Public Sub New()

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, _
    ByVal context As StreamingContext)
        If info Is Nothing Then
            Throw New System.ArgumentNullException("info")
        End If
        name_value = CStr(info.GetValue("AltName", GetType(String)))
        ID_value = Fix(info.GetValue("AltID", GetType(Integer)))

    End Sub

    <SecurityPermission(SecurityAction.LinkDemand, _
    Flags:=SecurityPermissionFlag.SerializationFormatter)> _
    Public Overridable Sub GetObjectData _
    (ByVal info As SerializationInfo, _
    ByVal context As StreamingContext) _
    Implements ISerializable.GetObjectData
        If info Is Nothing Then
            Throw New System.ArgumentNullException("info")
        End If
        info.AddValue("AltName", "XXX")
        info.AddValue("AltID", 9999)

    End Sub

    Public Property Name() As String
            Return name_value
        End Get
        Set(ByVal value As String)
            name_value = value
        End Set
    End Property

    Public Property IdNumber() As Integer
            Return ID_value
        End Get
        Set(ByVal value As Integer)
            ID_value = value
        End Set
    End Property
End Class


SerializationInfo에 포함 된 모든 개체는 포맷터에 의해 자동으로 추적 되 고 serialize 됩니다.Any objects that are included in the SerializationInfo are automatically tracked and serialized by the formatter.

GetObjectData를 호출 하는 코드는 serialization 서비스를 제공 하기 위해 SecurityPermission 필요 합니다.Code that calls GetObjectData requires the SecurityPermission for providing serialization services. 연관된 열거형: SecurityPermissionFlag.SerializationFormatterAssociated enumeration: SecurityPermissionFlag.SerializationFormatter.


이 메서드가 전파 serialization 중의 개체 인스턴스당 한 번만 호출할 수는 보장 되지 않습니다.It is not guaranteed that this method will be called only once per object instance during serialization. 따라서 메서드는 해당 동작 되도록 라고 하는 횟수에 관계 없이 동일한 방식으로 구현 되어야 합니다.Therefore, the method should be implemented in such a way that its behavior will be the same regardless of the number of times it is called.

적용 대상

추가 정보