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

定义

SerializationInfo 添加一个值。Adds a value into the SerializationInfo.

重载

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

将一个值添加到 SerializationInfo 存储中,其中 valuename 相关联,并串行化为 TypetypeAdds 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)

SerializationInfo 存储添加一个 64 位无符号整数值。Adds a 64-bit unsigned integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 32 位无符号整数值。Adds a 32-bit unsigned integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 16 位无符号整数值。Adds a 16-bit unsigned integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个单精度浮点值。Adds a single-precision floating-point value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 8 位带符号整数值。Adds an 8-bit signed integer value into the SerializationInfo store.

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

将指定的对象添加到与指定的名称关联的 SerializationInfo 存储。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)

SerializationInfo 存储添加一个 64 位带符号整数值。Adds a 64-bit signed integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 32 位带符号整数值。Adds a 32-bit signed integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 16 位带符号整数值。Adds a 16-bit signed integer value into the SerializationInfo store.

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

SerializationInfo 存储添加一个双精度浮点值。Adds a double-precision floating-point value into the SerializationInfo store.

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

SerializationInfo 存储添加一个十进制值。Adds a decimal value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 DateTime 值。Adds a DateTime value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 Unicode 字符值。Adds a Unicode character value into the SerializationInfo store.

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

SerializationInfo 存储添加一个 8 位无符号整数值。Adds an 8-bit unsigned integer value into the SerializationInfo store.

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

SerializationInfo 存储中添加一个布尔值。Adds a Boolean value into the SerializationInfo store.

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

将一个值添加到 SerializationInfo 存储中,其中 valuename 相关联,并串行化为 TypetypeAdds 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

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Object Object Object Object

要串行化的值。The value to be serialized. 会自动串行化此对象的所有子级。Any children of this object will automatically be serialized.

type
Type Type Type Type

要与当前对象相关联的 TypeThe Type to associate with the current object. 此参数必须始终是该对象本身的类型或其中一个基类的类型。This parameter must always be the type of the object itself or of one of its base classes.

异常

如果 nametypenullIf name or type is null.

已有值与 name 相关联。A value has already been associated with name.

注解

已分配的类型始终是对象的类型或它的某个父级。The assigned type is always the type of the object, or one of its parents.

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

重要

此 API 不符合 CLS。

SerializationInfo 存储添加一个 64 位无符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
UInt64 UInt64 UInt64 UInt64

要序列化的 UInt64 值。The UInt64 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

重要

此 API 不符合 CLS。

SerializationInfo 存储添加一个 32 位无符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
UInt32 UInt32 UInt32 UInt32

要序列化的 UInt32 值。The UInt32 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

示例

下面的示例使用AddValue方法自定义类型的序列化。The following example uses the AddValue method to customize the serialization of a type. 此代码将一个字符串和一个整数添加到SerializationInfo ISerializable接口的GetObjectData方法中的类的实例。The code adds a string and an integer to an instance of the SerializationInfo class in the GetObjectData method of the ISerializable interface. 此代码还使用GetValue方法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.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

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

重要

此 API 不符合 CLS。

SerializationInfo 存储添加一个 16 位无符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
UInt16 UInt16 UInt16 UInt16

要序列化的 UInt16 值。The UInt16 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Single Single Single Single

要序列化的 Single 值。The single value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

重要

此 API 不符合 CLS。

SerializationInfo 存储添加一个 8 位带符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
SByte SByte SByte SByte

要序列化的 Sbyte 值。The Sbyte value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

将指定的对象添加到与指定的名称关联的 SerializationInfo 存储。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Object Object Object Object

要串行化的值。The value to be serialized. 会自动串行化此对象的所有子级。Any children of this object will automatically be serialized.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

value参数中包含的对象被序列化为value返回的类型。The object contained in the value parameter is serialized as the type returned by value.

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 64 位带符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Int64 Int64 Int64 Int64

要序列化的 Int64 值。The Int64 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 32 位带符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Int32 Int32 Int32 Int32

要序列化的 Int32 值。The Int32 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

示例

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

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 16 位带符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Int16 Int16 Int16 Int16

要序列化的 Int16 值。The Int16 value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Double Double Double Double

要序列化的 Double 值。The double value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Decimal Decimal Decimal Decimal

要序列化的十进制值。The decimal value to serialize.

异常

如果 name 参数为 nullIf The name parameter is null.

如果已有值与 name 相关联。If a value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 DateTime 值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
DateTime DateTime DateTime DateTime

要序列化的 DateTime 值。The DateTime value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 Unicode 字符值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Char Char Char Char

要序列化的字符值。The character value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

SerializationInfo 存储添加一个 8 位无符号整数值。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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Byte Byte Byte Byte

要序列化的字节值。The byte value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。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)

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)

参数

name
String String String String

要与值关联的名称,因此它可在以后被反序列化。The name to associate with the value, so it can be deserialized later.

value
Boolean Boolean Boolean Boolean

要序列化的布尔值。The Boolean value to serialize.

异常

已有值与 name 相关联。A value has already been associated with name.

注解

如果使用仅大小写不同的名称添加了两个值, 则不会引发异常, 这是建议的做法。If two values are added with names that differ only by case, no exception will be thrown, which is not a recommended practice. 但是, 添加具有相同名称的两个值将导致SerializationException引发。However, adding two values with the exact same name will cause the SerializationException to be thrown. 例如: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  

适用于