IDataContractSurrogate.GetObjectToSerialize(Object, Type) Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
During serialization, returns an object that substitutes the specified object.
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
Parameters
- obj
- Object
The object to substitute.
Returns
The substituted object that will be serialized. The object must be serializable by the DataContractSerializer. For example, it must be marked with the DataContractAttribute attribute or other mechanisms that the serializer recognizes.
Examples
The following example shows an implementation of the GetObjectToSerialize method.
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
Remarks
This method must not return null
because on deserialization the data will be cast to type Object and an InvalidCastException is thrown.
Applies to
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기