IDataContractSurrogate.GetObjectToSerialize(Object, Type) 方法

定义

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

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

参数

obj
Object

要替换的对象。

targetType
Type

应将被替换的对象分配到的 Type

返回

Object

将要序列化的被替换对象。 该对象必须可由 DataContractSerializer 序列化。 例如,必须用 DataContractAttribute 属性或序列化程序可识别的其他机制对它进行标记。

示例

下面的示例演示 GetObjectToSerialize 方法的实现。

public object GetObjectToSerialize(object obj, Type targetType)
{
        Console.WriteLine("GetObjectToSerialize Invoked");
        Console.WriteLine("\t type name: {0}", obj.ToString());
        Console.WriteLine("\t target type: {0}", targetType.Name);
        // This method is called on serialization.
        // If Person is not being serialized...
        if (obj is Person )
        {
            Console.WriteLine("\t returning PersonSurrogated");
            // ... use the XmlSerializer to perform the actual serialization.
            PersonSurrogated  ps = new PersonSurrogated();
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            StringWriter sw = new StringWriter();
            xs.Serialize(sw, (Person)obj );
            ps.xmlData = sw.ToString();
            return ps;
        }
        return obj;
    }
Public Function GetObjectToSerialize(ByVal obj As Object, _
    ByVal targetType As Type) As Object _
    Implements IDataContractSurrogate.GetObjectToSerialize
    Console.WriteLine("GetObjectToSerialize Invoked")
    Console.WriteLine(vbTab & "type name: {0}", obj.ToString)
    Console.WriteLine(vbTab & "target type: {0}", targetType.Name)
    ' This method is called on serialization.
    ' If Person is not being serialized...
    If TypeOf obj Is Person Then
        Console.WriteLine(vbTab & "returning PersonSurrogated")
        ' ... use the XmlSerializer to perform the actual serialization.
        Dim ps As New PersonSurrogated()
        Dim xs As New XmlSerializer(GetType(Person))
        Dim sw As New StringWriter()
        xs.Serialize(sw, CType(obj, Person))
        ps.xmlData = sw.ToString()
        Return ps
    End If
    Return obj

End Function

注解

此方法不能返回 null ,因为在反序列化时,数据将被强制转换为类型 Object 并引发一个 InvalidCastException

适用于