版本相容序列化回呼

資料合約程式設計模型完整支援 BinaryFormatterSoapFormatter 類別所支援的版本相容序列化回呼方法。

版本相容的屬性

回呼屬性有四個。 每個屬性都可以套用至序列化/還原序列化引擎在不同時間呼叫的方法。 下表說明何時使用各個屬性。

屬性 呼叫對應方法的時機
OnSerializingAttribute 在序列化型別之前呼叫。
OnSerializedAttribute 在序列化型別之後呼叫。
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

另請參閱