데이터 계약 프로그래밍 모델은 BinaryFormatter와 SoapFormatter 클래스가 지원하는 버전 호환 serialization 콜백 메서드를 완벽하게 지원합니다.
Version-Tolerant 특성
4개의 콜백 특성이 있습니다. 각 특성은 serialization/deserialization 엔진이 여러 번 호출하는 메서드에 적용할 수 있습니다. 아래 표에서는 각 특성을 사용하는 시기를 설명합니다.
특성 | 해당 메서드가 호출되는 경우 |
---|---|
OnSerializingAttribute | 유형을 직렬화하기 전에 호출됩니다. |
OnSerializedAttribute | 형식을 serialize한 후 호출합니다. |
OnDeserializingAttribute | 형식을 역직렬화하기 전에 호출합니다. |
OnDeserializedAttribute | 형식을 역직렬화한 후 호출합니다. |
메서드는 매개 변수를 StreamingContext 수락해야 합니다.
이러한 메서드는 주로 버전 관리 또는 초기화에 사용하기 위한 것입니다. 역직렬화 중에는 생성자가 호출되지 않습니다. 따라서 이러한 멤버에 대한 데이터가 들어오는 스트림에서 누락된 경우(예: 데이터가 일부 데이터 멤버가 누락된 형식의 이전 버전에서 가져온 경우) 데이터 멤버가 올바르게 초기화되지 않을 수 있습니다(의도한 기본값으로). 이 문제를 해결하려면 다음 예제와 OnDeserializingAttribute같이 표시된 콜백 메서드를 사용합니다.
위의 각 콜백 특성을 사용하여 형식당 하나의 메서드만 표시할 수 있습니다.
예시
// 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