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

定義

加入值至 SerializationInfoAdds 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)

將 64 位元不帶正負號的整數值新增至 SerializationInfo 存放區。Adds a 64-bit unsigned integer value into the SerializationInfo store.

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

將 32 位元不帶正負號的整數值新增至 SerializationInfo 存放區。Adds a 32-bit unsigned integer value into the SerializationInfo store.

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

加入 16 位元不帶正負號的整數值至 SerializationInfo 存放區。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)

加入 8 位元帶正負號的整數值至 SerializationInfo 存放區。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)

將 64 位元帶正負號的整數值新增至 SerializationInfo 存放區。Adds a 64-bit signed integer value into the SerializationInfo store.

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

將 32 位元帶正負號的整數值新增至 SerializationInfo 存放區。Adds a 32-bit signed integer value into the SerializationInfo store.

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

加入 16 位元帶正負號的整數值 (Signed Integer) 至 SerializationInfo 存放區。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)

加入 DateTime 值至 SerializationInfo 存放區。Adds a DateTime value into the SerializationInfo store.

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

加入 Unicode 字元值至 SerializationInfo 存放區。Adds a Unicode character value into the SerializationInfo store.

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

加入 8 位元不帶正負號的整數值 (Unsigned Integer) 至 SerializationInfo 存放區。Adds an 8-bit unsigned integer value into the SerializationInfo store.

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

加入布林值 (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 規範。

將 64 位元不帶正負號的整數值新增至 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)

參數

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 規範。

將 32 位元不帶正負號的整數值新增至 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)

參數

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類別內GetObjectData方法ISerializable介面。The code adds a string and an integer to an instance of the SerializationInfo class in the GetObjectData method of the ISerializable interface. 程式碼也會使用GetValue方法來擷取值,從SerializationInfoThe 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

備註

如果加入的兩個值的差異只在於名稱情況下,任何例外狀況會擲回,這不是建議的做法。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 規範。

加入 16 位元不帶正負號的整數值至 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)

參數

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

要序列化的單精準浮點數值。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 規範。

加入 8 位元帶正負號的整數值至 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)

參數

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參數會序列化為傳回的型別valueThe 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)

將 64 位元帶正負號的整數值新增至 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)

參數

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)

將 32 位元帶正負號的整數值新增至 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)

參數

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)

加入 16 位元帶正負號的整數值 (Signed Integer) 至 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)

參數

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

要序列化的雙精度浮點數值。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)

加入 DateTime 值至 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)

參數

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)

加入 Unicode 字元值至 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)

參數

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)

加入 8 位元不帶正負號的整數值 (Unsigned Integer) 至 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)

參數

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)

加入布林值 (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  

適用於