バージョン トレラントなシリアル化コールバック

データ コントラクトのプログラミング モデルでは、BinaryFormatter クラスと SoapFormatter クラスがサポートする、複数のバージョンに対応するシリアル化コールバック メソッドが完全にサポートされます。

複数のバージョンに対応する属性

4 つのコールバック属性があります。 各属性は、さまざまなタイミングでシリアル化エンジンまたは逆シリアル化エンジンが呼び出すメソッドに適用できます。 次の表では、各属性を使用するタイミングについて説明します。

属性 対応するメソッドが呼び出されるタイミング
OnSerializingAttribute 型をシリアル化する前に呼び出されます。
OnSerializedAttribute 型をシリアル化した後に呼び出されます。
OnDeserializingAttribute 型を逆シリアル化する前に呼び出されます。
OnDeserializedAttribute 型を逆シリアル化した後に呼び出されます。

メソッドは、StreamingContext パラメーターを受け入れる必要があります。

これらのメソッドは、主にバージョン管理と初期化に使用するためのものです。 逆シリアル化時にコンストラクターは呼び出されません。 このため、データ メンバーのデータが受信ストリームにない場合、たとえば、データの送信元が、一部のデータ メンバーが不足している前のバージョンの型である場合、そのデータ メンバーを目的の既定値に適切に初期化できないことがあります。 これを修正するには、次の例で示すように、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

関連項目