ISerializable 接口
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
允许对象通过二进制和 XML 序列化控制其自己的序列化和反序列化。
public interface class ISerializable
public interface ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable
type ISerializable = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type ISerializable = interface
Public Interface ISerializable
- 派生
- 属性
示例
下面的代码示例演示如何使用 ISerializable 接口为类定义自定义二进制序列化行为。
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;
ref class SingletonSerializationHelper;
// There should be only one instance of this type per AppDomain.
[Serializable]
public ref class Singleton sealed: public ISerializable
{
private:
// This is the one instance of this type.
static Singleton^ theOneObject = gcnew Singleton;
public:
// Here are the instance fields.
String^ someString;
Int32 someNumber;
private:
// Private constructor allowing this type to construct the singleton.
Singleton()
{
// Do whatever is necessary to initialize the singleton.
someString = "This is a String* field";
someNumber = 123;
}
public:
// A method returning a reference to the singleton.
static Singleton^ GetSingleton()
{
return theOneObject;
}
// A method called when serializing a Singleton.
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::LinkDemand,
Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
virtual void GetObjectData( SerializationInfo^ info, StreamingContext context )
{
// Instead of serializing this Object*, we will
// serialize a SingletonSerializationHelp instead.
info->SetType( SingletonSerializationHelper::typeid );
// No other values need to be added.
}
// NOTE: ISerializable*'s special constructor is NOT necessary
// because it's never called
};
[Serializable]
private ref class SingletonSerializationHelper sealed: public IObjectReference
{
public:
// This Object* has no fields (although it could).
// GetRealObject is called after this Object* is deserialized
virtual Object^ GetRealObject( StreamingContext context )
{
// When deserialiing this Object*, return a reference to
// the singleton Object* instead.
return Singleton::GetSingleton();
}
};
[STAThread]
int main()
{
FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
try
{
// Construct a BinaryFormatter and use it
// to serialize the data to the stream.
BinaryFormatter^ formatter = gcnew BinaryFormatter;
// Create an array with multiple elements refering to
// the one Singleton Object*.
array<Singleton^>^a1 = {Singleton::GetSingleton(),Singleton::GetSingleton()};
// This displays S"True".
Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a1[ 0 ] == a1[ 1 ]) );
// Serialize the array elements.
formatter->Serialize( fs, a1 );
// Deserialize the array elements.
fs->Position = 0;
array<Singleton^>^a2 = (array<Singleton^>^)formatter->Deserialize( fs );
// This displays S"True".
Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a2[ 0 ] == a2[ 1 ]) );
// This displays S"True".
Console::WriteLine( "Do all array elements refer to the same Object? {0}", (a1[ 0 ] == a2[ 0 ]) );
}
catch ( SerializationException^ e )
{
Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
throw;
}
finally
{
fs->Close();
}
return 0;
}
using System;
using System.Text;
using System.IO;
// Add references to Soap and Binary formatters.
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap ;
using System.Runtime.Serialization;
[Serializable]
public class MyItemType : ISerializable
{
public MyItemType()
{
// Empty constructor required to compile.
}
// The value to serialize.
private string myProperty_value;
public string MyProperty
{
get { return myProperty_value; }
set { myProperty_value = value; }
}
// Implement this method to serialize data. The method is called
// on serialization.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("props", myProperty_value, typeof(string));
}
// The special constructor is used to deserialize values.
public MyItemType(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
myProperty_value = (string) info.GetValue("props", typeof(string));
}
}
// This is a console application.
public static class Test
{
static void Main()
{
// This is the name of the file holding the data. You can use any file extension you like.
string fileName = "dataStuff.myData";
// Use a BinaryFormatter or SoapFormatter.
IFormatter formatter = new BinaryFormatter();
//IFormatter formatter = new SoapFormatter();
Test.SerializeItem(fileName, formatter); // Serialize an instance of the class.
Test.DeserializeItem(fileName, formatter); // Deserialize the instance.
Console.WriteLine("Done");
Console.ReadLine();
}
public static void SerializeItem(string fileName, IFormatter formatter)
{
// Create an instance of the type and serialize it.
MyItemType t = new MyItemType();
t.MyProperty = "Hello World";
FileStream s = new FileStream(fileName , FileMode.Create);
formatter.Serialize(s, t);
s.Close();
}
public static void DeserializeItem(string fileName, IFormatter formatter)
{
FileStream s = new FileStream(fileName, FileMode.Open);
MyItemType t = (MyItemType)formatter.Deserialize(s);
Console.WriteLine(t.MyProperty);
}
}
Imports System.Text
Imports System.IO
' Add references to Soap and Binary formatters.
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Runtime.Serialization
<Serializable()> _
Public Class MyItemType
Implements ISerializable
' Empty constructor required to compile.
Public Sub New()
End Sub
' The value to serialize.
Private myProperty_value As String
Public Property MyProperty() As String
Get
Return myProperty_value
End Get
Set(value As String)
myProperty_value = value
End Set
End Property
' Implement this method to serialize data. The method is called
' on serialization.
Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
' Use the AddValue method to specify serialized values.
info.AddValue("props", myProperty_value, GetType(String))
End Sub
' The special constructor is used to deserialize values.
Public Sub New(info As SerializationInfo, context As StreamingContext)
' Reset the property value using the GetValue method.
myProperty_value = DirectCast(info.GetValue("props", GetType(String)), String)
End Sub
End Class
' This is a console application.
Public Class Test
Public Shared Sub Main()
' This is the name of the file holding the data. You can use any file extension you like.
Dim fileName As String = "dataStuff.myData"
' Use a BinaryFormatter or SoapFormatter.
Dim formatter As IFormatter = New BinaryFormatter()
' Dim formatter As IFormatter = New SoapFormatter()
Test.SerializeItem(fileName, formatter)
' Serialize an instance of the class.
Test.DeserializeItem(fileName, formatter)
' Deserialize the instance.
Console.WriteLine("Done")
Console.ReadLine()
End Sub
Public Shared Sub SerializeItem(fileName As String, formatter As IFormatter)
' Create an instance of the type and serialize it.
Dim myType As New MyItemType()
myType.MyProperty = "Hello World"
Dim fs As New FileStream(fileName, FileMode.Create)
formatter.Serialize(fs, myType)
fs.Close()
End Sub
Public Shared Sub DeserializeItem(fileName As String, formatter As IFormatter)
Dim fs As New FileStream(fileName, FileMode.Open)
Dim myType As MyItemType = DirectCast(formatter.Deserialize(fs), MyItemType)
Console.WriteLine(myType.MyProperty)
End Sub
End Class
注解
任何可能使用二进制或 XML 序列化进行序列化的类都必须使用 SerializableAttribute标记。 如果类需要控制其二进制或 XML 序列化过程,它可以实现 ISerializable 接口。 在 Formatter 序列化时调用 GetObjectData ,并使用表示 对象所需的所有数据填充提供的 SerializationInfo 。 使用 Formatter 图形中 对象的类型创建 SerializationInfo 。 需要为自己发送代理的对象可以使用 FullTypeName 上的 SerializationInfo 和 AssemblyName 方法来更改传输的信息。
对于类继承,可以序列化派生自实现 的基类的 ISerializable类。 在这种情况下,派生类应在其 的 实现中调用 的GetObjectDataGetObjectData基类实现。 否则,基类中的数据将不会序列化。
接口 ISerializable 意味着具有签名 constructor (SerializationInfo information, StreamingContext context)
的构造函数。 在反序列化时,只有在格式化程序反序列化 中的数据之后, SerializationInfo 才会调用当前构造函数。 一般情况下,如果 类不是 sealed
,则此构造函数应protected
为 。
无法保证对象的反序列化顺序。 例如,如果一个类型引用尚未反序列化的类型,则会发生异常。 如果要创建具有此类依赖项的类型,可以通过实现 IDeserializationCallback
接口和 OnDeserialization
方法来解决此问题。
序列化体系结构处理的对象类型与扩展 MarshalByRefObject 的类型相同 Object。 这些类型可以使用 标记, SerializableAttribute 并将 接口实现 ISerializable 为任何其他对象类型。 它们的对象状态将被捕获并保存到流中。
当通过 System.Runtime.Remoting使用这些类型时,远程处理基础结构会提供一个代理项,该代理优先于典型序列化,而是将代理序列化为 MarshalByRefObject。 代理项是一种帮助程序,它知道如何序列化和反序列化特定类型的对象。 在大多数情况下,该代理对用户不可见,其类型 ObjRef为 。
作为一种常规设计模式,使用可序列化属性和扩展 MarshalByRefObject标记类是不寻常的。 在结合这两个特征时,开发人员应仔细考虑可能的序列化和远程处理方案。 可能适用的一个 MemoryStream示例是 使用 。 虽然 (Stream 的MemoryStream基类) 从 MarshalByRefObject扩展,但可以捕获 状态MemoryStream并随时还原。 因此,将此流的状态序列化为数据库并在以后的某个时间点还原它可能有意义。 但是,通过远程处理使用时,将代理此类型的对象。
有关扩展 MarshalByRefObject的类的序列化的详细信息,请参阅 RemotingSurrogateSelector。 有关实现 ISerializable的详细信息,请参阅 自定义序列化。
注意
此接口不适用于使用 的 System.Text.JsonJSON 序列化。
实施者说明
实现此接口以允许对象参与其自己的序列化和反序列化。
方法
GetObjectData(SerializationInfo, StreamingContext) |
使用将目标对象序列化所需的数据填充 SerializationInfo。 |