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…then…else 控制结构测试 obj 值的类型是否为被代理的类型。 如果是,则根据需要转换该值并返回被替换的对象。 被替换的对象可以是新实例或同一个 obj 实例。

适用于