OnSerializingAttribute 类
定义
当应用于方法时,指定在序列化对象关系图中的对象期间调用该方法。When applied to a method, specifies that the method is during serialization of an object in an object graph. 相对于关系图中的其他对象,序列化的顺序是不确定的。The order of serialization relative to other objects in the graph is non-deterministic.
public ref class OnSerializingAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)]
public sealed class OnSerializingAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnSerializingAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)>]
type OnSerializingAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type OnSerializingAttribute = class
inherit Attribute
Public NotInheritable Class OnSerializingAttribute
Inherits Attribute
- 继承
- 属性
示例
下面的示例将 OnDeserializedAttribute 、 OnSerializingAttribute 、和属性应用于 OnSerializedAttribute OnDeserializingAttribute 类中的方法。The following example applies the OnDeserializedAttribute, OnSerializingAttribute, OnSerializedAttribute, and OnDeserializingAttribute attributes to methods in a class.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Test
{
public static void Main()
{
// Create a new TestSimpleObject object.
TestSimpleObject obj = new TestSimpleObject();
Console.WriteLine("\n Before serialization the object contains: ");
obj.Print();
// Open a file and serialize the object into binary format.
Stream stream = File.Open("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(stream, obj);
// Print the object again to see the effect of the
//OnSerializedAttribute.
Console.WriteLine("\n After serialization the object contains: ");
obj.Print();
// Set the original variable to null.
obj = null;
stream.Close();
// Open the file "DataFile.dat" and deserialize the object from it.
stream = File.Open("DataFile.dat", FileMode.Open);
// Deserialize the object from the data file.
obj = (TestSimpleObject)formatter.Deserialize(stream);
Console.WriteLine("\n After deserialization the object contains: ");
obj.Print();
Console.ReadLine();
}
catch (SerializationException se)
{
Console.WriteLine("Failed to serialize. Reason: " + se.Message);
throw;
}
catch (Exception exc)
{
Console.WriteLine("An exception occurred. Reason: " + exc.Message);
throw;
}
finally
{
stream.Close();
obj = null;
formatter = null;
}
}
}
// This is the object that will be serialized and deserialized.
[Serializable()]
public class TestSimpleObject
{
// This member is serialized and deserialized with no change.
public int member1;
// The value of this field is set and reset during and
// after serialization.
private string member2;
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
[NonSerialized()]
public string member3;
// This field is set to null, but populated after deserialization.
private string member4;
// Constructor for the class.
public TestSimpleObject()
{
member1 = 11;
member2 = "Hello World!";
member3 = "This is a nonserialized value";
member4 = null;
}
public void Print()
{
Console.WriteLine("member1 = '{0}'", member1);
Console.WriteLine("member2 = '{0}'", member2);
Console.WriteLine("member3 = '{0}'", member3);
Console.WriteLine("member4 = '{0}'", member4);
}
[OnSerializing()]
internal void OnSerializingMethod(StreamingContext context)
{
member2 = "This value went into the data file during serialization.";
}
[OnSerialized()]
internal void OnSerializedMethod(StreamingContext context)
{
member2 = "This value was reset after serialization.";
}
[OnDeserializing()]
internal void OnDeserializingMethod(StreamingContext context)
{
member3 = "This value was set during deserialization";
}
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
member4 = "This value was set after deserialization.";
}
}
// Output:
// Before serialization the object contains:
// member1 = '11'
// member2 = 'Hello World!'
// member3 = 'This is a nonserialized value'
// member4 = ''
//
// After serialization the object contains:
// member1 = '11'
// member2 = 'This value was reset after serialization.'
// member3 = 'This is a nonserialized value'
// member4 = ''
//
// After deserialization the object contains:
// member1 = '11'
// member2 = 'This value went into the data file during serialization.'
// member3 = 'This value was set during deserialization'
// member4 = 'This value was set after deserialization.'
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Public Class Test
Public Shared Sub Main()
' Create a new TestSimpleObject object.
Dim obj As New TestSimpleObject()
Console.WriteLine(vbLf + " Before serialization the object contains: ")
obj.Print()
' Open a file and serialize the object into binary format.
Dim stream As Stream = File.Open("DataFile.dat", FileMode.Create)
Dim formatter As New BinaryFormatter()
Try
formatter.Serialize(stream, obj)
' Print the object again to see the effect of the
'OnSerializedAttribute.
Console.WriteLine(vbLf + " After serialization the object contains: ")
obj.Print()
' Set the original variable to null.
obj = Nothing
stream.Close()
' Open the file "DataFile.dat" and deserialize the object from it.
stream = File.Open("DataFile.dat", FileMode.Open)
' Deserialize the object from the data file.
obj = CType(formatter.Deserialize(stream), TestSimpleObject)
Console.WriteLine(vbLf + " After deserialization the object contains: ")
obj.Print()
Console.ReadLine()
Catch se As SerializationException
Console.WriteLine("Failed to serialize. Reason: " + se.Message)
Throw
Catch exc As Exception
Console.WriteLine("An exception occurred. Reason: " + exc.Message)
Throw
Finally
stream.Close()
obj = Nothing
formatter = Nothing
End Try
End Sub
End Class
' This is the object that will be serialized and deserialized.
<Serializable()> _
Public Class TestSimpleObject
' This member is serialized and deserialized with no change.
Public member1 As Integer
' The value of this field is set and reset during and
' after serialization.
Private member2 As String
' This field is not serialized. The OnDeserializedAttribute
' is used to set the member value after serialization.
<NonSerialized()> _
Public member3 As String
' This field is set to null, but populated after deserialization.
Private member4 As String
' Constructor for the class.
Public Sub New()
member1 = 11
member2 = "Hello World!"
member3 = "This is a nonserialized value"
member4 = Nothing
End Sub
Public Sub Print()
Console.WriteLine("member1 = '{0}'", member1)
Console.WriteLine("member2 = '{0}'", member2)
Console.WriteLine("member3 = '{0}'", member3)
Console.WriteLine("member4 = '{0}'", member4)
End Sub
<OnSerializing()> _
Friend Sub OnSerializingMethod(ByVal context As StreamingContext)
member2 = "This value went into the data file during serialization."
End Sub
<OnSerialized()> _
Friend Sub OnSerializedMethod(ByVal context As StreamingContext)
member2 = "This value was reset after serialization."
End Sub
<OnDeserializing()> _
Friend Sub OnDeserializingMethod(ByVal context As StreamingContext)
member3 = "This value was set during deserialization"
End Sub
<OnDeserialized()> _
Friend Sub OnDeserializedMethod(ByVal context As StreamingContext)
member4 = "This value was set after deserialization."
End Sub
End Class
' Output:
' Before serialization the object contains:
' member1 = '11'
' member2 = 'Hello World!'
' member3 = 'This is a nonserialized value'
' member4 = ''
'
' After serialization the object contains:
' member1 = '11'
' member2 = 'This value was reset after serialization.'
' member3 = 'This is a nonserialized value'
' member4 = ''
'
' After deserialization the object contains:
' member1 = '11'
' member2 = 'This value went into the data file during serialization.'
' member3 = 'This value was set during deserialization'
' member4 = 'This value was set after deserialization.'
注解
在 OnSerializingAttribute 进行序列化之前,使用来处理对象。Use the OnSerializingAttribute to manipulate the object before serialization occurs.
若要使用 OnSerializingAttribute ,该方法必须包含 StreamingContext 参数。To use the OnSerializingAttribute, the method must contain a StreamingContext parameter. 特性标记要由序列化基础结构调用的方法,并 StreamingContext 提供有关进行序列化的类型的其他数据。The attribute marks the method to be called by the serialization infrastructure and the StreamingContext provides additional data about the type of serialization taking place. 下面的代码演示了用法:The usage is shown in the following code:
[OnSerializing]
private void SetValuesOnSerializing(StreamingContext context)
{
// Code not shown.
}
<OnSerializing()> _
Private Sub SetValuesOnSerializing(ByVal context As StreamingContext)
' Code not shown.
End Sub
备注
在代码中,可以使用 OnSerializing 一词来代替较长的 OnSerializingAttribute。In your code, you can use the word OnSerializing instead of the longer OnSerializingAttribute.
使用二进制序列化时,如果序列化对象相等,二进制序列化进程将忽略对方法的调用 onSerializing 。When using binary serialization, the binary serialization process omits the call to the onSerializing method when the serialized objects are equal. 因此,将 BinaryFormatter 类型与方法一起使用时 equals (或 Object.GetHashCode) 例如,结果可能是未定义的行为。Therefore, when using the BinaryFormatter type with the equals method (or Object.GetHashCode) for example, the result may be undefined behavior.
构造函数
| OnSerializingAttribute() |
初始化 OnSerializingAttribute 类的新实例。Initializes a new instance of the OnSerializingAttribute class. |
属性
| TypeId |
在派生类中实现时,获取此 Attribute 的唯一标识符。When implemented in a derived class, gets a unique identifier for this Attribute. (继承自 Attribute) |
方法
| Equals(Object) |
返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object. (继承自 Attribute) |
| GetHashCode() |
返回此实例的哈希代码。Returns the hash code for this instance. (继承自 Attribute) |
| GetType() |
获取当前实例的 Type。Gets the Type of the current instance. (继承自 Object) |
| IsDefaultAttribute() |
在派生类中重写时,指示此实例的值是否是派生类的默认值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (继承自 Attribute) |
| Match(Object) |
当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (继承自 Attribute) |
| MemberwiseClone() |
创建当前 Object 的浅表副本。Creates a shallow copy of the current Object. (继承自 Object) |
| ToString() |
返回表示当前对象的字符串。Returns a string that represents the current object. (继承自 Object) |
显式接口实现
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers. (继承自 Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can be used to get the type information for an interface. (继承自 Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1). (继承自 Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object. (继承自 Attribute) |