数据协定编程模型完全支持BinaryFormatter和SoapFormatter类所支持的版本容错序列化回调方法。
版本容错属性
共有四个回调属性。 每个属性都可以应用于序列化/反序列化引擎在不同时间调用的方法。 下表说明了何时使用每个属性。
特征 | 调用相应的方法时 |
---|---|
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