データ コントラクト プログラミング モデルは、 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