IDataContractSurrogate.GetDeserializedObject(Object, Type) 方法

定义

在反序列化期间,返回一个替代指定对象的对象。

public:
 System::Object ^ GetDeserializedObject(System::Object ^ obj, Type ^ targetType);
public object GetDeserializedObject(object obj, Type targetType);
abstract member GetDeserializedObject : obj * Type -> obj
Public Function GetDeserializedObject (obj As Object, targetType As Type) As Object

参数

obj
Object

要替换的反序列化对象。

targetType
Type

Type应将替换的对象分配给该对象。

返回

替换的反序列化对象。 此对象必须是可由 DataContractSerializer该对象序列化的类型。 例如,它必须使用序列化程序识别的属性或其他机制进行标记 DataContractAttribute

示例

以下示例演示方法的 GetDeserializedObject 实现。

public object GetDeserializedObject(Object obj , Type targetType)
{
    Console.WriteLine("GetDeserializedObject invoked");
    // This method is called on deserialization.
    // If PersonSurrogated is being deserialized...
    if (obj is PersonSurrogated)
        {
            //... use the XmlSerializer to do the actual deserialization.
            PersonSurrogated ps = (PersonSurrogated)obj;
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            return (Person)xs.Deserialize(new StringReader(ps.xmlData));
        }
        return obj;
}
Public Function GetDeserializedObject(ByVal obj As Object, _
    ByVal targetType As Type) As Object Implements _
    IDataContractSurrogate.GetDeserializedObject
    Console.WriteLine("GetDeserializedObject invoked")
    ' This method is called on deserialization.
    ' If PersonSurrogated is being deserialized...
    If TypeOf obj Is PersonSurrogated Then
        Console.WriteLine(vbTab & "returning PersonSurrogated")
        '... use the XmlSerializer to do the actual deserialization.
        Dim ps As PersonSurrogated = CType(obj, PersonSurrogated)
        Dim xs As New XmlSerializer(GetType(Person))
        Return CType(xs.Deserialize(New StringReader(ps.xmlData)), Person)
    End If
    Return obj

End Function

注解

在简单实现中,使用 if...然后。。。else 控制结构,用于测试该值是否 obj 为代理项类型。 如果是,请根据需要对其进行转换并返回替换的对象。 替换的对象可以是新实例或同一 obj 实例。

适用于