SerializationInfo 类

定义

存储对对象进行序列化或反序列化所需的全部数据。 此类不能被继承。

public ref class SerializationInfo sealed
public sealed class SerializationInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
type SerializationInfo = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type SerializationInfo = class
Public NotInheritable Class SerializationInfo
继承
SerializationInfo
属性

示例

下面的代码示例演示 SerializationInfo 了各种值的自定义序列化和反序列化。

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

注解

此类由具有自定义序列化行为的对象使用。 方法GetObjectDataISerializableISerializationSurrogate用要序列化的每个信息片段的名称、类型和值填充SerializationInfo存储区。 在反序列化期间,适当的函数可以提取此信息。

对象使用AddValue方法在序列化时添加到SerializationInfo存储区,SerializationInfo并使用GetValue方法从存储区中提取。

有关自定义序列化的详细信息,请参阅 自定义序列化

构造函数

SerializationInfo(Type, IFormatterConverter)

创建 SerializationInfo 类的新实例。

SerializationInfo(Type, IFormatterConverter, Boolean)

初始化 SerializationInfo 类的新实例。

属性

AssemblyName

仅在序列化期间获取或设置要序列化的类型的程序集名称。

FullTypeName

获取或设置要序列化的 Type 的全名。

IsAssemblyNameSetExplicit

获取是否已显式设置程序集名称。

IsFullTypeNameSetExplicit

获取是否已显式设置完整类型名称。

MemberCount

获取已添加到 SerializationInfo 存储中的成员数目。

ObjectType

返回要串行化的对象的类型。

方法

AddValue(String, Boolean)

SerializationInfo 存储中添加一个布尔值。

AddValue(String, Byte)

SerializationInfo 存储添加一个 8 位无符号整数值。

AddValue(String, Char)

SerializationInfo 存储添加一个 Unicode 字符值。

AddValue(String, DateTime)

SerializationInfo 存储添加一个 DateTime 值。

AddValue(String, Decimal)

SerializationInfo 存储添加一个十进制值。

AddValue(String, Double)

SerializationInfo 存储添加一个双精度浮点值。

AddValue(String, Int16)

SerializationInfo 存储添加一个 16 位带符号整数值。

AddValue(String, Int32)

SerializationInfo 存储添加一个 32 位带符号整数值。

AddValue(String, Int64)

SerializationInfo 存储添加一个 64 位带符号整数值。

AddValue(String, Object)

将指定的对象添加到与指定的名称关联的 SerializationInfo 存储。

AddValue(String, Object, Type)

将一个值添加到 SerializationInfo 存储中,其中 valuename 相关联,并串行化为 Typetype

AddValue(String, SByte)

SerializationInfo 存储添加一个 8 位带符号整数值。

AddValue(String, Single)

SerializationInfo 存储添加一个单精度浮点值。

AddValue(String, UInt16)

SerializationInfo 存储添加一个 16 位无符号整数值。

AddValue(String, UInt32)

SerializationInfo 存储添加一个 32 位无符号整数值。

AddValue(String, UInt64)

SerializationInfo 存储添加一个 64 位无符号整数值。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetBoolean(String)

SerializationInfo 存储中检索一个布尔值。

GetByte(String)

SerializationInfo 存储中检索一个 8 位无符号整数值。

GetChar(String)

SerializationInfo 存储中检索一个 Unicode 字符值。

GetDateTime(String)

DateTime 存储中检索一个 SerializationInfo 值。

GetDecimal(String)

SerializationInfo 存储中检索一个十进制值。

GetDouble(String)

SerializationInfo 存储中检索一个双精度浮点值。

GetEnumerator()

返回一个 SerializationInfoEnumerator,用于循环访问 SerializationInfo 存储中的名称/值对。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetInt16(String)

SerializationInfo 存储中检索一个 16 位带符号整数值。

GetInt32(String)

SerializationInfo 存储中检索一个 32 位带符号整数值。

GetInt64(String)

SerializationInfo 存储中检索一个 64 位带符号整数值。

GetSByte(String)

SerializationInfo 存储中检索一个 8 位带符号整数值。

GetSingle(String)

SerializationInfo 存储中检索一个单精度浮点值。

GetString(String)

String 存储中检索一个 SerializationInfo 值。

GetType()

获取当前实例的 Type

(继承自 Object)
GetUInt16(String)

SerializationInfo 存储中检索一个 16 位无符号整数值。

GetUInt32(String)

SerializationInfo 存储中检索一个 32 位无符号整数值。

GetUInt64(String)

SerializationInfo 存储中检索一个 64 位无符号整数值。

GetValue(String, Type)

SerializationInfo 存储中检索一个值。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
SetType(Type)

设置要序列化的对象的 Type

ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅