共用方式為


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,應該要指派給已取代物件的型別。

傳回

將序列化的已取代物件。 這個物件必須由 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 擲回 。

適用於