共用方式為


Version-Tolerant 串行化回呼

數據合約程式設計模型完全支援 BinaryFormatterSoapFormatter 類別支援的版本容錯序列化回呼方法。

Version-Tolerant 屬性

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

屬性 當呼叫相應的方法時
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

另請參閱