ExtensionDataObject 클래스

정의

버전이 있는 데이터 계약이 새 멤버가 추가되어 확장될 경우 계약의 데이터를 저장합니다.

public ref class ExtensionDataObject sealed
public sealed class ExtensionDataObject
type ExtensionDataObject = class
Public NotInheritable Class ExtensionDataObject
상속
ExtensionDataObject

예제

다음 코드는 직렬화 가능한 형식(PersonVersion2)의 두 번째 버전인 형식(Person)의 인스턴스를 serialize합니다. 두 번째 버전에는 첫 번째 버전에 없는 추가 데이터(ID 필드)가 포함되어 있습니다. 그런 다음, 코드는 XML 문서를 개체로 Person 역직렬화한 다음, 추가 데이터를 포함하여 개체를 즉시 다시 역직렬화합니다. 마지막으로 코드는 새 XML을 개체로 PersonVersion2 역직렬화하고 전체 데이터를 콘솔에 기록하여 데이터가 이전 버전의 형식을 왕복했음을 증명합니다. 특성은 DataContractAttribute 원래 클래스와 동일한 이름 및 Namespace 네임스페이스로 설정된 속성과 함께 Name 적용해야 합니다.

using System;
using System.Xml;
using System.Runtime.Serialization;
using System.IO;

// Implement the IExtensibleDataObject interface
// to store the extra data for future versions.
[DataContract(
    Name = "Person",
    Namespace = "http://www.cohowinery.com/employees")]
class Person : IExtensibleDataObject
{
    // To implement the IExtensibleDataObject interface,
    // you must implement the ExtensionData property. The property
    // holds data from future versions of the class for backward
    // compatibility.
    private ExtensionDataObject extensionDataObject_value;
    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionDataObject_value;
        }
        set
        {
            extensionDataObject_value = value;
        }
    }
    [DataMember]
    public string Name;
}

// The second version of the class adds a new field. The field's
// data is stored in the ExtensionDataObject field of
// the first version (Person). You must also set the Name property
// of the DataContractAttribute to match the first version.
// If necessary, also set the Namespace property so that the
// name of the contracts is the same.
[DataContract(Name = "Person",
    Namespace = "http://www.cohowinery.com/employees")]
class PersonVersion2 : IExtensibleDataObject
{
    // Best practice: add an Order number to new members.
    [DataMember(Order=2)]
    public int ID;

    [DataMember]
    public string Name;

    private ExtensionDataObject extensionDataObject_value;
    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionDataObject_value;
        }
        set
        {
            extensionDataObject_value = value;
        }
    }
}
public sealed class Program
{
    private Program()
    {
        // Private constructor to prevent creation of this class.
    }

    public static void Main()
    {
        try
        {
            WriteVersion2("V2.xml");
            WriteToVersion1("v2.xml");
            ReadVersion2("v2.xml");
        }
        catch (SerializationException exc)
        {
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace);
        }
        finally
        {
            Console.ReadLine();
        }
    }

    // Create an instance of the version 2.0 class. It has
    // extra data (ID field) that version 1.0 does
    // not understand.
    static void WriteVersion2(string path)
    {
        Console.WriteLine("Creating a version 2 object");
        PersonVersion2 p2 = new PersonVersion2();
        p2.Name = "Elizabeth";
        p2.ID = 2006;

        Console.WriteLine("Object data includes an ID");
        Console.WriteLine("\t Name: {0}", p2.Name);
        Console.WriteLine("\t ID: {0} \n", p2.ID);
        // Create an instance of the DataContractSerializer.
        DataContractSerializer ser =
            new DataContractSerializer(typeof(PersonVersion2));

        Console.WriteLine("Serializing the v2 object to a file. \n\n");
        FileStream fs = new FileStream(path, FileMode.Create);
        ser.WriteObject(fs, p2);
        fs.Close();
    }

    // Deserialize version 2 data to a version 1 object.
    static void WriteToVersion1(string path)
    {
        // Create the serializer using the version 1 type.
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));

        FileStream fs = new FileStream(path, FileMode.Open);
        XmlDictionaryReader reader =
           XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        Console.WriteLine
            ("Deserializing v2 data to v1 object. \n\n");

        Person p1 = (Person)ser.ReadObject(reader, false);

        Console.WriteLine("V1 data has only a Name field.");
        Console.WriteLine("But the v2 data is stored in the ");
        Console.WriteLine("ExtensionData property. \n\n");
        Console.WriteLine("\t Name: {0} \n", p1.Name);

        fs.Close();

        // Change data in the object.
        p1.Name = "John";
        Console.WriteLine("Changed the Name value to 'John' ");
        Console.Write("and reserializing the object to version 2 \n\n");
        // Reserialize the object.
        fs = new FileStream(path, FileMode.Create);
        ser.WriteObject(fs, p1);
        fs.Close();
    }

    // Deserialize a version 2.0 object.
    public static void ReadVersion2(string path)
    {
        FileStream fs = new FileStream(path, FileMode.Open);
        DataContractSerializer ser = new DataContractSerializer(typeof(PersonVersion2));

        Console.WriteLine("Deserializing new data to version 2 \n\n");
        PersonVersion2 p2 = (PersonVersion2)ser.ReadObject(fs);
        fs.Close();

        Console.WriteLine("The data includes the old ID field value. \n");
        Console.WriteLine("\t (New) Name: {0}", p2.Name);
        Console.WriteLine("\t ID: {0} \n", p2.ID);
    }
}
' Implement the IExtensibleDataObject interface 
' to store the extra data for future versions.
<DataContract(Name := "Person", [Namespace] := "http://www.cohowinery.com/employees")>  _
Class Person
    Implements IExtensibleDataObject
    ' To implement the IExtensibleDataObject interface,
    ' you must implement the ExtensionData property. The property
    ' holds data from future versions of the class for backward
    ' compatibility.
    Private extensionDataObject_value As ExtensionDataObject
    
    Public Property ExtensionData() As ExtensionDataObject _
       Implements IExtensibleDataObject.ExtensionData
        Get
            Return extensionDataObject_value
        End Get
        Set
            extensionDataObject_value = value
        End Set
    End Property
    <DataMember()>  _
    Public Name As String
End Class 

' The second version of the class adds a new field. The field's 
' data is stored in the ExtensionDataObject field of
' the first version (Person). You must also set the Name property 
' of the DataContractAttribute to match the first version. 
' If necessary, also set the Namespace property so that the 
' name of the contracts is the same.

<DataContract(Name := "Person", [Namespace] := "http://www.cohowinery.com/employees")>  _
Class PersonVersion2
    Implements IExtensibleDataObject

    ' Best practice: add an Order number to new members.
    <DataMember(Order:=2)>  _
    Public ID As Integer
    
    <DataMember()>  _
    Public Name As String
    
    Private extensionDataObject_value As ExtensionDataObject
    
    Public Property ExtensionData() As ExtensionDataObject _
       Implements IExtensibleDataObject.ExtensionData
        Get
            Return extensionDataObject_value
        End Get
        Set
            extensionDataObject_value = value
        End Set
    End Property
End Class 

NotInheritable Public Class Program

    ' Private constructor to prevent creation of this class.
    Private Sub New() 
    
    End Sub 
    
    
    Public Shared Sub Main() 
        Try
            WriteVersion2("V2.xml")
            WriteToVersion1("v2.xml")
            ReadVersion2("v2.xml")
        Catch exc As SerializationException
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace)
        Finally
            Console.ReadLine()
        End Try
    
    End Sub 
    
    ' Create an instance of the version 2.0 class. It has  
    ' extra data (ID field) that version 1.0 does 
    ' not understand.
    Shared Sub WriteVersion2(ByVal path As String) 
        Console.WriteLine("Creating a version 2 object")
        Dim p2 As New PersonVersion2()
        p2.Name = "Elizabeth"
        p2.ID = 2006
        
        Console.WriteLine("Object data includes an ID")
        Console.WriteLine(vbTab + " Name: {0}", p2.Name)
        Console.WriteLine(vbTab + " ID: {0} " + vbLf, p2.ID)
        ' Create an instance of the DataContractSerializer.
        Dim ser As New DataContractSerializer(GetType(PersonVersion2))
        
        Console.WriteLine("Serializing the v2 object to a file. " + vbLf + vbLf)
        Dim fs As New FileStream(path, FileMode.Create)
        ser.WriteObject(fs, p2)
        fs.Close()
    End Sub 
    
    ' Deserialize version 2 data to a version 1 object.
    Shared Sub WriteToVersion1(ByVal path As String) 
        ' Create the serializer using the version 1 type.
        Dim ser As New DataContractSerializer(GetType(Person))
        
        Dim fs As New FileStream(path, FileMode.Open)
        Dim reader As XmlDictionaryReader = _
            XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
        Console.WriteLine("Deserializing v2 data to v1 object. " + vbLf + vbLf)
        
        Dim p1 As Person = CType(ser.ReadObject(reader, False), Person)
        
        Console.WriteLine("V1 data has only a Name field.")
        Console.WriteLine("But the v2 data is stored in the ")
        Console.WriteLine("ExtensionData property. " + vbLf + vbLf)
        Console.WriteLine(vbTab + " Name: {0} " + vbLf, p1.Name)
        
        reader.Close()
        fs.Close()
        
        ' Change data in the object.
        p1.Name = "John"
        Console.WriteLine("Changed the Name value to 'John' ")
        Console.Write("and reserializing the object to version 2 " + vbLf + vbLf)
        ' Reserialize the object.
        fs = New FileStream(path, FileMode.Create)
        ser.WriteObject(fs, p1)
        fs.Close()
    
    End Sub 
    
    ' Deserialize a version 2.0 object. 
    Public Shared Sub ReadVersion2(ByVal path As String) 
        Dim fs As New FileStream(path, FileMode.Open)
        Dim ser As New DataContractSerializer(GetType(PersonVersion2))
        
        Console.WriteLine("Deserializing new data to version 2 " + vbLf + vbLf)
        Dim p2 As PersonVersion2 = CType(ser.ReadObject(fs), PersonVersion2)
        fs.Close()
        
        Console.WriteLine("The data includes the old ID field value. " + vbLf)
        Console.WriteLine(vbTab + " (New) Name: {0}", p2.Name)
        Console.WriteLine(vbTab + " ID: {0} " + vbLf, p2.ID)
    
    End Sub 
End Class

설명

ExtensionDataObject 직렬화 작업 중에 발생하는 XmlObjectSerializer 추가 데이터를 저장하는 구조입니다. 이 구조는 serialization에서 serialize된 인스턴스에 추가 데이터를 쓰는 데 사용됩니다. 구조체는 인터페이스의 속성에 ExtensionData 의해 반환됩니다 IExtensibleDataObject .

메서드

Equals(Object)

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

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

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

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

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

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

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

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

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

(다음에서 상속됨 Object)

적용 대상

추가 정보