SerializationInfo.AddValue SerializationInfo.AddValue SerializationInfo.AddValue SerializationInfo.AddValue Method

Definición

Agrega un valor a SerializationInfo.Adds a value into the SerializationInfo.

Sobrecargas

AddValue(String, Object, Type) AddValue(String, Object, Type) AddValue(String, Object, Type)

Agrega un valor al almacén SerializationInfo, donde value está asociado a name y se serializa con Typetype.Adds a value into the SerializationInfo store, where value is associated with name and is serialized as being of Typetype.

AddValue(String, UInt64) AddValue(String, UInt64) AddValue(String, UInt64) AddValue(String, UInt64)

Agrega un valor entero de 64 bits sin signo al almacén SerializationInfo.Adds a 64-bit unsigned integer value into the SerializationInfo store.

AddValue(String, UInt32) AddValue(String, UInt32) AddValue(String, UInt32) AddValue(String, UInt32)

Agrega un valor entero de 32 bits sin signo al almacén SerializationInfo.Adds a 32-bit unsigned integer value into the SerializationInfo store.

AddValue(String, UInt16) AddValue(String, UInt16) AddValue(String, UInt16) AddValue(String, UInt16)

Agrega un valor entero de 16 bits sin signo al almacén SerializationInfo.Adds a 16-bit unsigned integer value into the SerializationInfo store.

AddValue(String, Single) AddValue(String, Single) AddValue(String, Single) AddValue(String, Single)

Agrega un valor de punto flotante de precisión sencilla al almacén SerializationInfo.Adds a single-precision floating-point value into the SerializationInfo store.

AddValue(String, SByte) AddValue(String, SByte) AddValue(String, SByte) AddValue(String, SByte)

Agrega un valor entero de 8 bits con signo al almacén SerializationInfo.Adds an 8-bit signed integer value into the SerializationInfo store.

AddValue(String, Object) AddValue(String, Object) AddValue(String, Object) AddValue(String, Object)

Agrega el objeto especificado al almacén SerializationInfo, donde se le asocia un nombre especificado.Adds the specified object into the SerializationInfo store, where it is associated with a specified name.

AddValue(String, Int64) AddValue(String, Int64) AddValue(String, Int64) AddValue(String, Int64)

Agrega un valor entero de 64 bits con signo al almacén SerializationInfo.Adds a 64-bit signed integer value into the SerializationInfo store.

AddValue(String, Int32) AddValue(String, Int32) AddValue(String, Int32) AddValue(String, Int32)

Agrega un valor entero de 32 bits con signo al almacén SerializationInfo.Adds a 32-bit signed integer value into the SerializationInfo store.

AddValue(String, Int16) AddValue(String, Int16) AddValue(String, Int16) AddValue(String, Int16)

Agrega un valor entero de 16 bits con signo al almacén SerializationInfo.Adds a 16-bit signed integer value into the SerializationInfo store.

AddValue(String, Double) AddValue(String, Double) AddValue(String, Double) AddValue(String, Double)

Agrega un valor de punto flotante de precisión doble al almacén SerializationInfo.Adds a double-precision floating-point value into the SerializationInfo store.

AddValue(String, Decimal) AddValue(String, Decimal) AddValue(String, Decimal) AddValue(String, Decimal)

Agrega un valor decimal al almacén SerializationInfo.Adds a decimal value into the SerializationInfo store.

AddValue(String, DateTime) AddValue(String, DateTime) AddValue(String, DateTime) AddValue(String, DateTime)

Agrega un valor DateTime al almacén SerializationInfo.Adds a DateTime value into the SerializationInfo store.

AddValue(String, Char) AddValue(String, Char) AddValue(String, Char) AddValue(String, Char)

Agrega un valor de carácter Unicode al almacén SerializationInfo.Adds a Unicode character value into the SerializationInfo store.

AddValue(String, Byte) AddValue(String, Byte) AddValue(String, Byte) AddValue(String, Byte)

Agrega un valor entero de 8 bits sin signo al almacén SerializationInfo.Adds an 8-bit unsigned integer value into the SerializationInfo store.

AddValue(String, Boolean) AddValue(String, Boolean) AddValue(String, Boolean) AddValue(String, Boolean)

Agrega un valor booleano al almacén SerializationInfo.Adds a Boolean value into the SerializationInfo store.

AddValue(String, Object, Type) AddValue(String, Object, Type) AddValue(String, Object, Type)

Agrega un valor al almacén SerializationInfo, donde value está asociado a name y se serializa con Typetype.Adds a value into the SerializationInfo store, where value is associated with name and is serialized as being of Typetype.

public:
 void AddValue(System::String ^ name, System::Object ^ value, Type ^ type);
public void AddValue (string name, object value, Type type);
member this.AddValue : string * obj * Type -> unit

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Object Object Object Object

Valor que se va a serializar.The value to be serialized. Automáticamente se serializarán todos los elementos secundarios de este objeto.Any children of this object will automatically be serialized.

type
Type Type Type Type

Type que se va a asociar al objeto actual.The Type to associate with the current object. Este parámetro debe ser siempre el tipo del objeto en sí o una de sus clases base.This parameter must always be the type of the object itself or of one of its base classes.

Excepciones

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

El tipo asignado es siempre el tipo del objeto, o uno de sus objetos primarios.The assigned type is always the type of the object, or one of its parents.

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, UInt64) AddValue(String, UInt64) AddValue(String, UInt64) AddValue(String, UInt64)

Importante

Esta API no es conforme a CLS.

Agrega un valor entero de 64 bits sin signo al almacén SerializationInfo.Adds a 64-bit unsigned integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::UInt64 value);
[System.CLSCompliant(false)]
public void AddValue (string name, ulong value);
member this.AddValue : string * uint64 -> unit
Public Sub AddValue (name As String, value As ULong)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
UInt64 UInt64 UInt64 UInt64

Valor UInt64 que se va a serializar.The UInt64 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, UInt32) AddValue(String, UInt32) AddValue(String, UInt32) AddValue(String, UInt32)

Importante

Esta API no es conforme a CLS.

Agrega un valor entero de 32 bits sin signo al almacén SerializationInfo.Adds a 32-bit unsigned integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::UInt32 value);
[System.CLSCompliant(false)]
public void AddValue (string name, uint value);
member this.AddValue : string * uint32 -> unit
Public Sub AddValue (name As String, value As UInteger)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
UInt32 UInt32 UInt32 UInt32

Valor UInt32 que se va a serializar.The UInt32 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Ejemplos

En el ejemplo siguiente se usa el AddValue método para personalizar la serialización de un tipo.The following example uses the AddValue method to customize the serialization of a type. El código agrega una cadena y un entero a una instancia de la SerializationInfo clase en el GetObjectData método de la ISerializable interfaz.The code adds a string and an integer to an instance of the SerializationInfo class in the GetObjectData method of the ISerializable interface. El código también usa el GetValue método para recuperar valores desde el SerializationInfo.The code also uses the GetValue method to retrieve values from the SerializationInfo.

using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.IO;

[assembly: SecurityPermission(
SecurityAction.RequestMinimum, Execution = true)]
namespace ISerializableExample
{
    class Program
    {
        public static void Main()
        {
            try
            {
                Run();
            }
            catch (Exception exc)
            {
                Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace);
            }
            finally
            {
                Console.WriteLine("Press Enter to exit....");
                Console.ReadLine();
            }
        }

        static void Run()
        {            
            BinaryFormatter binaryFmt = new BinaryFormatter();
            Person p = new Person();
            p.IdNumber = 1010;
            p.Name = "AAAAA";
            FileStream fs = new FileStream
                ("Person.xml", FileMode.OpenOrCreate);
            binaryFmt.Serialize(fs, p);
            fs.Close();
            Console.WriteLine
                ("Original Name: {0}, Original ID: {1}", p.Name, p.IdNumber);

            // Deserialize.
            fs = new FileStream
                ("Person.xml", FileMode.OpenOrCreate);
            Person p2 = (Person)binaryFmt.Deserialize(fs);
                Console.WriteLine("New Name: {0}, New ID: {1}", p2.Name, p2.IdNumber);
            fs.Close();
            }
        }
    [Serializable]
    public class Person : ISerializable
    {
        private string name_value;
        private int ID_value;

        public Person() { }
        protected Person(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new System.ArgumentNullException("info");
            name_value = (string)info.GetValue("AltName", typeof(string));
            ID_value = (int)info.GetValue("AltID", typeof(int));
        }

        [SecurityPermission(SecurityAction.LinkDemand,
            Flags = SecurityPermissionFlag.SerializationFormatter)]
        public virtual void GetObjectData(
        SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new System.ArgumentNullException("info");
            info.AddValue("AltName", "XXX");
            info.AddValue("AltID", 9999);
        }

        public string Name
        {
            get { return name_value; }
            set { name_value = value; }
        }

        public int IdNumber
        {
            get { return ID_value; }
            set { ID_value = value; }
        }
    }
}
Imports System
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Security.Permissions
Imports System.IO

<Assembly: SecurityPermission _
(SecurityAction.RequestMinimum, Execution:=True)> 

Class Program

    Public Shared Sub Main()
        Try
            Run()
        Catch exc As Exception
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace)
        Finally
            Console.WriteLine("Press Enter to exit....")
            Console.ReadLine()
        End Try

    End Sub

    Shared Sub Run()
        Dim binaryFmt As New BinaryFormatter()
        Dim p As New Person()
        p.IdNumber = 1010
        p.Name = "AAAAA"
        Dim fs As New FileStream("Person.xml", FileMode.OpenOrCreate)
        binaryFmt.Serialize(fs, p)
        fs.Close()
        Console.WriteLine _
        ("Original Name: {0}, Original ID: {1}", p.Name, p.IdNumber)

        ' Deserialize.
        fs = New FileStream("Person.xml", FileMode.OpenOrCreate)
        Dim p2 As Person = CType(binaryFmt.Deserialize(fs), Person)
        Console.WriteLine("New Name: {0}, New ID: {1}", _
        p2.Name, p2.IdNumber)
        fs.Close()
    End Sub
End Class

<Serializable()> _
Public Class Person
    Implements ISerializable
    Private name_value As String
    Private ID_value As Integer

    Public Sub New()

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, _
    ByVal context As StreamingContext)
        If info Is Nothing Then
            Throw New System.ArgumentNullException("info")
        End If
        name_value = CStr(info.GetValue("AltName", GetType(String)))
        ID_value = Fix(info.GetValue("AltID", GetType(Integer)))

    End Sub

    <SecurityPermission(SecurityAction.LinkDemand, _
    Flags:=SecurityPermissionFlag.SerializationFormatter)> _
    Public Overridable Sub GetObjectData _
    (ByVal info As SerializationInfo, _
    ByVal context As StreamingContext) _
    Implements ISerializable.GetObjectData
        If info Is Nothing Then
            Throw New System.ArgumentNullException("info")
        End If
        info.AddValue("AltName", "XXX")
        info.AddValue("AltID", 9999)

    End Sub

    Public Property Name() As String
        Get
            Return name_value
        End Get
        Set(ByVal value As String)
            name_value = value
        End Set
    End Property

    Public Property IdNumber() As Integer
        Get
            Return ID_value
        End Get
        Set(ByVal value As Integer)
            ID_value = value
        End Set
    End Property
End Class

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, UInt16) AddValue(String, UInt16) AddValue(String, UInt16) AddValue(String, UInt16)

Importante

Esta API no es conforme a CLS.

Agrega un valor entero de 16 bits sin signo al almacén SerializationInfo.Adds a 16-bit unsigned integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::UInt16 value);
[System.CLSCompliant(false)]
public void AddValue (string name, ushort value);
member this.AddValue : string * uint16 -> unit
Public Sub AddValue (name As String, value As UShort)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
UInt16 UInt16 UInt16 UInt16

Valor UInt16 que se va a serializar.The UInt16 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Single) AddValue(String, Single) AddValue(String, Single) AddValue(String, Single)

Agrega un valor de punto flotante de precisión sencilla al almacén SerializationInfo.Adds a single-precision floating-point value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, float value);
public void AddValue (string name, float value);
member this.AddValue : string * single -> unit
Public Sub AddValue (name As String, value As Single)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Single Single Single Single

Valor single que se va a serializar.The single value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, SByte) AddValue(String, SByte) AddValue(String, SByte) AddValue(String, SByte)

Importante

Esta API no es conforme a CLS.

Agrega un valor entero de 8 bits con signo al almacén SerializationInfo.Adds an 8-bit signed integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::SByte value);
[System.CLSCompliant(false)]
public void AddValue (string name, sbyte value);
member this.AddValue : string * sbyte -> unit
Public Sub AddValue (name As String, value As SByte)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
SByte SByte SByte SByte

Valor Sbyte que se va a serializar.The Sbyte value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Object) AddValue(String, Object) AddValue(String, Object) AddValue(String, Object)

Agrega el objeto especificado al almacén SerializationInfo, donde se le asocia un nombre especificado.Adds the specified object into the SerializationInfo store, where it is associated with a specified name.

public:
 void AddValue(System::String ^ name, System::Object ^ value);
public void AddValue (string name, object value);
member this.AddValue : string * obj -> unit
Public Sub AddValue (name As String, value As Object)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Object Object Object Object

Valor que se va a serializar.The value to be serialized. Automáticamente se serializarán todos los elementos secundarios de este objeto.Any children of this object will automatically be serialized.

Excepciones

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

El objeto contenido en el value parámetro se serializa como el tipo devuelto por value.The object contained in the value parameter is serialized as the type returned by value.

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Int64) AddValue(String, Int64) AddValue(String, Int64) AddValue(String, Int64)

Agrega un valor entero de 64 bits con signo al almacén SerializationInfo.Adds a 64-bit signed integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, long value);
public void AddValue (string name, long value);
member this.AddValue : string * int64 -> unit
Public Sub AddValue (name As String, value As Long)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Int64 Int64 Int64 Int64

Valor Int64 que se va a serializar.The Int64 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Int32) AddValue(String, Int32) AddValue(String, Int32) AddValue(String, Int32)

Agrega un valor entero de 32 bits con signo al almacén SerializationInfo.Adds a 32-bit signed integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, int value);
public void AddValue (string name, int value);
member this.AddValue : string * int -> unit
Public Sub AddValue (name As String, value As Integer)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Int32 Int32 Int32 Int32

Valor Int32 que se va a serializar.The Int32 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Ejemplos

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

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Int16) AddValue(String, Int16) AddValue(String, Int16) AddValue(String, Int16)

Agrega un valor entero de 16 bits con signo al almacén SerializationInfo.Adds a 16-bit signed integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, short value);
public void AddValue (string name, short value);
member this.AddValue : string * int16 -> unit
Public Sub AddValue (name As String, value As Short)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Int16 Int16 Int16 Int16

Valor Int16 que se va a serializar.The Int16 value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Double) AddValue(String, Double) AddValue(String, Double) AddValue(String, Double)

Agrega un valor de punto flotante de precisión doble al almacén SerializationInfo.Adds a double-precision floating-point value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, double value);
public void AddValue (string name, double value);
member this.AddValue : string * double -> unit
Public Sub AddValue (name As String, value As Double)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Double Double Double Double

Valor double que se va a serializar.The double value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Decimal) AddValue(String, Decimal) AddValue(String, Decimal) AddValue(String, Decimal)

Agrega un valor decimal al almacén SerializationInfo.Adds a decimal value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::Decimal value);
public void AddValue (string name, decimal value);
member this.AddValue : string * decimal -> unit
Public Sub AddValue (name As String, value As Decimal)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Decimal Decimal Decimal Decimal

Valor decimal que se va a serializar.The decimal value to serialize.

Excepciones

Si el parámetro name es null.If The name parameter is null.

Si ya se ha asociado un valor a name.If a value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, DateTime) AddValue(String, DateTime) AddValue(String, DateTime) AddValue(String, DateTime)

Agrega un valor DateTime al almacén SerializationInfo.Adds a DateTime value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, DateTime value);
public void AddValue (string name, DateTime value);
member this.AddValue : string * DateTime -> unit
Public Sub AddValue (name As String, value As DateTime)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
DateTime DateTime DateTime DateTime

Valor DateTime que se va a serializar.The DateTime value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Char) AddValue(String, Char) AddValue(String, Char) AddValue(String, Char)

Agrega un valor de carácter Unicode al almacén SerializationInfo.Adds a Unicode character value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, char value);
public void AddValue (string name, char value);
member this.AddValue : string * char -> unit
Public Sub AddValue (name As String, value As Char)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Char Char Char Char

Valor de carácter que se va a serializar.The character value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Byte) AddValue(String, Byte) AddValue(String, Byte) AddValue(String, Byte)

Agrega un valor entero de 8 bits sin signo al almacén SerializationInfo.Adds an 8-bit unsigned integer value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, System::Byte value);
public void AddValue (string name, byte value);
member this.AddValue : string * byte -> unit
Public Sub AddValue (name As String, value As Byte)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Byte Byte Byte Byte

Valor de byte que se va a serializar.The byte value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown.

AddValue(String, Boolean) AddValue(String, Boolean) AddValue(String, Boolean) AddValue(String, Boolean)

Agrega un valor booleano al almacén SerializationInfo.Adds a Boolean value into the SerializationInfo store.

public:
 void AddValue(System::String ^ name, bool value);
public void AddValue (string name, bool value);
member this.AddValue : string * bool -> unit
Public Sub AddValue (name As String, value As Boolean)

Parámetros

name
String String String String

Nombre que se asocia al valor de modo que se pueda deserializar posteriormente.The name to associate with the value, so it can be deserialized later.

value
Boolean Boolean Boolean Boolean

Valor booleano que se va a serializar.The Boolean value to serialize.

Excepciones

El parámetro name es null.The name parameter is null.

Ya se ha asociado un valor a name.A value has already been associated with name.

Comentarios

Si se agregan dos valores con los nombres que se diferencien solo por caso, no se producirá ninguna excepción, que no es una práctica recomendada.If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. Sin embargo, agregar dos valores con el mismo nombre producirá el SerializationException que se produzca.However, adding two values with the exact same name will cause the SerializationException to be thrown. Por ejemplo:For example:

void ISerializable.GetObject(SerializationInfo info, StreamingContext context)  
{  
   // This will not cause an exception to be thrown.  
   info.AddValue("ABC", true);  
   info.AddValue("abc", false);  
   // However, this will cause the SerializationException to be thrown.  
   info.AddValue("XYZ", true);  
   info.AddValue("XYZ", false);  
}  
Private Sub GetObjectData(ByVal info As SerializationInfo, _  
ByVal context As StreamingContext)  
   ' This will not cause an exception to be thrown.  
   info.AddValue("ABC", "upper case")  
   info.AddValue("abc", "lower case")  
   ' However, this will cause the SerializationException to be thrown.  
   info.AddValue("XYZ", "same case")  
   info.AddValue("XYZ", "same case")  
End Sub  

Se aplica a