SerializationInfo Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Almacena todos los datos necesarios para serializar o deserializar un objeto. Esta clase no puede heredarse.
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
- Herencia
-
SerializationInfo
- Atributos
Ejemplos
En el ejemplo de código siguiente se muestra para la SerializationInfo serialización personalizada y la deserialización de varios valores.
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
Comentarios
Los objetos usan esta clase con un comportamiento de serialización personalizado. El GetObjectData método de o ISerializable ISerializationSurrogate rellena el SerializationInfo almacén con el nombre, el tipo y el valor de cada fragmento de información que desea serializar. Durante la deserialización, la función adecuada puede extraer esta información.
Los objetos se agregan al SerializationInfo almacén en tiempo de serialización mediante los AddValue métodos y extraídos del almacén en la SerializationInfo deserialización mediante los GetValue métodos .
Para obtener más información sobre cómo personalizar la serialización, consulte Serialización personalizada.
Constructores
SerializationInfo(Type, IFormatterConverter) |
Crea una nueva instancia de la clase SerializationInfo. |
SerializationInfo(Type, IFormatterConverter, Boolean) |
Inicializa una nueva instancia de la clase SerializationInfo. |
Propiedades
AssemblyName |
Obtiene o establece el nombre de ensamblado del tipo que se va a serializar sólo durante la serialización. |
FullTypeName |
Obtiene o establece el nombre completo del Type que se va a serializar. |
IsAssemblyNameSetExplicit |
Obtiene si el nombre del ensamblado se ha establecido explícitamente. |
IsFullTypeNameSetExplicit |
Obtiene si el nombre del tipo completo se ha establecido explícitamente. |
MemberCount |
Obtiene el número de miembros que se han agregado al almacén SerializationInfo. |
ObjectType |
Devuelve el tipo del objeto que se va a serializar. |
Métodos
AddValue(String, Boolean) |
Agrega un valor booleano al almacén SerializationInfo. |
AddValue(String, Byte) |
Agrega un valor entero de 8 bits sin signo al almacén SerializationInfo. |
AddValue(String, Char) |
Agrega un valor de carácter Unicode al almacén SerializationInfo. |
AddValue(String, DateTime) |
Agrega un valor DateTime al almacén SerializationInfo. |
AddValue(String, Decimal) |
Agrega un valor decimal al almacén SerializationInfo. |
AddValue(String, Double) |
Agrega un valor de punto flotante de precisión doble al almacén SerializationInfo. |
AddValue(String, Int16) |
Agrega un valor entero de 16 bits con signo al almacén SerializationInfo. |
AddValue(String, Int32) |
Agrega un valor entero de 32 bits con signo al almacén SerializationInfo. |
AddValue(String, Int64) |
Agrega un valor entero de 64 bits con signo al almacén SerializationInfo. |
AddValue(String, Object) |
Agrega el objeto especificado al almacén SerializationInfo, donde se le asocia un nombre especificado. |
AddValue(String, Object, Type) |
Agrega un valor al almacén SerializationInfo, donde |
AddValue(String, SByte) |
Agrega un valor entero de 8 bits con signo al almacén SerializationInfo. |
AddValue(String, Single) |
Agrega un valor de punto flotante de precisión sencilla al almacén SerializationInfo. |
AddValue(String, UInt16) |
Agrega un valor entero de 16 bits sin signo al almacén SerializationInfo. |
AddValue(String, UInt32) |
Agrega un valor entero de 32 bits sin signo al almacén SerializationInfo. |
AddValue(String, UInt64) |
Agrega un valor entero de 64 bits sin signo al almacén SerializationInfo. |
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
GetBoolean(String) |
Recupera un valor booleano del almacén SerializationInfo. |
GetByte(String) |
Recupera un valor entero de 8 bits sin signo del almacén SerializationInfo. |
GetChar(String) |
Recupera un valor de carácter Unicode del almacén SerializationInfo. |
GetDateTime(String) |
Recupera un valor DateTime del almacén SerializationInfo. |
GetDecimal(String) |
Recupera un valor decimal del almacén SerializationInfo. |
GetDouble(String) |
Recupera un valor de punto flotante de precisión doble del almacén SerializationInfo. |
GetEnumerator() |
Devuelve un objeto SerializationInfoEnumerator que se utiliza para recorrer en iteración los pares de nombre y valor del almacén SerializationInfo. |
GetHashCode() |
Sirve como la función hash predeterminada. (Heredado de Object) |
GetInt16(String) |
Recupera un valor entero de 16 bits con signo del almacén SerializationInfo. |
GetInt32(String) |
Recupera un valor entero de 32 bits con signo del almacén SerializationInfo. |
GetInt64(String) |
Recupera un valor entero de 64 bits con signo del almacén SerializationInfo. |
GetSByte(String) |
Recupera un valor entero de 8 bits con signo del almacén SerializationInfo. |
GetSingle(String) |
Recupera un valor de punto flotante de precisión sencilla del almacén SerializationInfo. |
GetString(String) |
Recupera un valor String del almacén SerializationInfo. |
GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
GetUInt16(String) |
Recupera un valor entero de 16 bits sin signo del almacén SerializationInfo. |
GetUInt32(String) |
Recupera un valor entero de 32 bits sin signo del almacén SerializationInfo. |
GetUInt64(String) |
Recupera un valor entero de 64 bits sin signo del almacén SerializationInfo. |
GetValue(String, Type) |
Recupera un valor del almacén SerializationInfo. |
MemberwiseClone() |
Crea una copia superficial del Object actual. (Heredado de Object) |
SetType(Type) |
Establece el Type del objeto que se va a serializar. |
ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |