버전 독립적 Serialization 콜백

데이터 계약 프로그래밍 모델에서는 BinaryFormatterSoapFormatter 클래스에서 지원하는 버전 독립적 serialization 콜백 메서드를 완전히 지원합니다.

버전 독립적 특성

4개의 콜백 특성이 있습니다. 각 특성은 다양한 시기에 serialization/deserialization 엔진에서 호출하는 메서드에 적용할 수 있습니다. 다음 표에서는 각 특성을 사용하는 시기에 대해 설명합니다.

Attribute 해당 메서드를 호출하는 시기
OnSerializingAttribute 형식을 serialize하기 전에 호출됩니다.
OnSerializedAttribute 형식을 serialize한 후에 호출됩니다.
OnDeserializingAttribute 형식을 역직렬화하기 전에 호출됩니다.
OnDeserializedAttribute 형식을 역직렬화한 후에 호출됩니다.

메서드에서는 StreamingContext 매개 변수를 받아야 합니다.

이 메서드는 주로 버전 지정 또는 초기화에 사용됩니다. deserialization을 수행하는 동안에는 생성자가 호출되지 않습니다. 따라서 들어오는 스트림에 이러한 멤버의 데이터가 없는 경우(예: 데이터가 일부 데이터 멤버가 없는 이전 버전의 형식으로부터 오는 경우) 데이터 멤버가 의도한 기본값으로 올바르게 초기화되지 않을 수 있습니다. 이 문제를 해결하려면 다음 예제처럼 OnDeserializingAttribute로 표시된 콜백 메서드를 사용합니다.

위의 각 콜백 특성에서 형식 당 1개의 메서드만 표시할 수 있습니다.

예시

// The following Data Contract is version 2 of an earlier data
// contract.
[DataContract]
public class Address
{
    [DataMember]
    public string Street;

    [DataMember]
    public string State;

    // This data member was added in version 2, and thus may be missing
    // in the incoming data if the data conforms to version 1 of the
    // Data Contract. Use the callback to add a default for this case.
    [DataMember(Order=2)]
    public string CountryRegion;

    // This method is used as a kind of constructor to initialize
    // a default value for the CountryRegion data member before
    // deserialization.
    [OnDeserializing]
    private void setDefaultCountryRegion(StreamingContext c)
    {
        CountryRegion = "Japan";
    }
}
' The following Data Contract is version 2 of an earlier data 
' contract.
<DataContract()> _
Public Class Address
    <DataMember()> _
    Public Street As String
    <DataMember()> _
    Public State As String

    ' This data member was added in version 2, and thus may be missing 
    ' in the incoming data if the data conforms to version 1 of the 
    ' Data Contract.
    <DataMember(Order:=2)> _
    Public CountryRegion As String

    ' This method is used as a kind of constructor to initialize
    ' a default value for the CountryRegion data member before 
    ' deserialization.
    <OnDeserializing()> _
    Private Sub setDefaultCountryRegion(ByVal c As StreamingContext)
        CountryRegion = "Japan"
    End Sub
End Class

참고 항목