ISerializable ISerializable ISerializable ISerializable Interface

定义

允许对象控制其自己的序列化和反序列化过程。Allows an object to control its own serialization and deserialization.

public interface class ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable
type ISerializable = interface
Public Interface ISerializable
派生
属性

示例

下面的代码示例演示如何使用ISerializable接口为类定义自定义序列化行为。The following code example demonstrates the use of the ISerializable interface to define custom serialization behavior for a class.

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

注解

任何可能会序列化的类必须用SerializableAttribute来标记。Any class that might be serialized must be marked with the SerializableAttribute. 如果某个类需要控制其序列化过程, 则它可以实现ISerializable接口。If a class needs to control its serialization process, it can implement the ISerializable interface. 在序列化GetObjectDataSerializationInfo调用, 并用表示对象所需的所有数据填充所提供的。 FormatterThe Formatter calls the GetObjectData at serialization time and populates the supplied SerializationInfo with all the data required to represent the object. 使用关系图中对象的类型Formatter SerializationInfo创建。The Formatter creates a SerializationInfo with the type of the object in the graph. 需要为自身发送代理的对象可以使用FullTypeNameAssemblyName方法SerializationInfo来更改传输的信息。Objects that need to send proxies for themselves can use the FullTypeName and AssemblyName methods on SerializationInfo to change the transmitted information.

对于类继承, 可以序列化派生自实现ISerializable的基类的类。In the case of class inheritance, it is possible to serialize a class that derives from a base class that implements ISerializable. 在这种情况下, 派生类应在其GetObjectData GetObjectData实现中调用的基类实现。In this case, the derived class should call the base class implementation of GetObjectData inside its implementation of GetObjectData. 否则, 基类中的数据将不会序列化。Otherwise, the data from the base class will not be serialized.

接口表示具有签名构造函数的构造函数 (SerializationInfo信息、 StreamingContext上下文)。 ISerializableThe ISerializable interface implies a constructor with the signature constructor (SerializationInfo information, StreamingContext context). 在反序列化时, 仅在格式化程序对中SerializationInfo的数据进行反序列化后调用当前构造函数。At deserialization time, the current constructor is called only after the data in the SerializationInfo has been deserialized by the formatter. 通常, 如果类未密封, 应保护此构造函数。In general, this constructor should be protected if the class is not sealed.

无法保证反序列化对象的顺序。The order in which objects are deserialized cannot be guaranteed. 例如, 如果一种类型引用尚未反序列化的类型, 则将发生异常。For example, if one type references a type that has not been deserialized yet, an exception will occur. 如果要创建具有此类依赖项的类型, 则可以通过实现IDeserializationCallback接口OnDeserialization和方法来解决该问题。If you are creating types that have such dependencies, you can work around the problem by implementing the IDeserializationCallback interface and the OnDeserialization method.

序列化体系结构处理与扩展MarshalByRefObject Object的类型相同的对象类型。The serialization architecture handles object types that extend MarshalByRefObject the same as types that extend Object. 这些类型可以用SerializableAttribute进行标记, 并将ISerializable接口实现为任何其他对象类型。These types can be marked with the SerializableAttribute and implement the ISerializable interface as any other object type. 将捕获其对象状态并将其保存到流中。Their object state will be captured and persisted onto the stream.

当使用System.Runtime.Remoting这些类型时, 远程处理基础结构将提供抢先于典型序列化并改为将代理序列化为的MarshalByRefObject代理项。When these types are being used through System.Runtime.Remoting, the remoting infrastructure provides a surrogate that preempts typical serialization and instead serializes a proxy to the MarshalByRefObject. 代理项是了解如何序列化和反序列化特定类型的对象的帮助器。A surrogate is a helper that knows how to serialize and deserialize objects of a particular type. 在大多数情况下, 代理对用户不可见的类型ObjRef为。The proxy, invisible to the user in most cases, will be of type ObjRef.

作为常规设计模式, 类既可以使用可序列化属性进行标记又可以扩展MarshalByRefObject, 这种情况很常见。As a general design pattern, it would be unusual for a class to be both marked with the serializable attribute and extend MarshalByRefObject. 组合这两个特征时, 开发人员应仔细考虑可能的序列化和远程处理方案。Developers should think carefully about the possible serialization and remoting scenarios when combining these two characteristics. 其中可能适用的一个示例是使用MemoryStreamOne example where this might be applicable is with a MemoryStream. MemoryStream (Stream) 的基类从MarshalByRefObject扩展时, 可以捕获的状态MemoryStream并将其还原到。While the base class of MemoryStream (Stream) extends from MarshalByRefObject, it is possible to capture the state of a MemoryStream and restore it at will. 因此, 它可能有意义, 可以将此流的状态序列化为数据库, 并在以后的某个时间点还原。It might, therefore, be meaningful to serialize the state of this stream into a database and restore it at some later point in time. 但是, 当通过远程处理使用时, 将对此类型的对象进行代理。However, when used through remoting, an object of this type would be proxied.

有关扩展MarshalByRefObject的类序列化的详细信息, 请RemotingSurrogateSelector参阅。For more information about serialization of classes that extend MarshalByRefObject, see RemotingSurrogateSelector. 有关实现ISerializable的详细信息, 请参阅自定义序列化For more information about implementing ISerializable, see Custom Serialization.

实施者说明

实现此接口可使对象参与其自己的序列化和反序列化。Implement this interface to allow an object to take part in its own serialization and deserialization.

方法

GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

使用将目标对象序列化所需的数据填充 SerializationInfoPopulates a SerializationInfo with the data needed to serialize the target object.

适用于

另请参阅