SerializationInfoEnumerator SerializationInfoEnumerator SerializationInfoEnumerator SerializationInfoEnumerator Class

定義

針對解析 SerializationInfo 中的資料,提供易用的格式子 (Formatter) 機制。Provides a formatter-friendly mechanism for parsing the data in SerializationInfo. 這個類別無法被繼承。This class cannot be inherited.

public ref class SerializationInfoEnumerator sealed : System::Collections::IEnumerator
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfoEnumerator : System.Collections.IEnumerator
type SerializationInfoEnumerator = class
    interface IEnumerator
Public NotInheritable Class SerializationInfoEnumerator
Implements IEnumerator
繼承
SerializationInfoEnumeratorSerializationInfoEnumeratorSerializationInfoEnumeratorSerializationInfoEnumerator
屬性
實作

範例

下列程式碼範例示範如何使用FormatterServices類別才能正確序列化或還原序列化的物件的基底類別未實作ISerializable但衍生的類別。The following code example shows how to use the FormatterServices class in order to properly serialize or deserialize an object where the base class does not implement ISerializable but the derived class does.

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Reflection;
using namespace System::Security::Permissions;

// Person is a serializable base class.
[Serializable]
public ref class Person
{
private:
    String^ title;

public:
    Person(String^ title)
    {
        this->title = title;
    }

public:
    virtual String^ ToString() override
    {
        return String::Format("{0}", title);
    }
};

// Employee is a serializable class derived from Person.
[Serializable]
public ref class Employee : public Person
{
private:
    String^ title;

public:
    Employee(String^ title) : Person("Person")
    {
        this->title = title;
    }

public:
    virtual String^ ToString() override
    {
        return String::Format("{0} -> {1}", title, Person::ToString());
    }
};

// Manager is a serializable and ISerializable class derived from Employee.
[Serializable]
ref class Manager : public Employee, public ISerializable
{
private:
    String^ title;

public:
    Manager() : Employee("Employee")
    {
        this->title = "Manager";
    }

public:
    [SecurityPermission(SecurityAction::Demand, SerializationFormatter = true)]
    virtual void GetObjectData(SerializationInfo^ info, StreamingContext context)
    {
        // Serialize the desired values for this class.
        info->AddValue("title", title);

        // Get the set of serializable members for the class and base classes.
        Type^ thisType = this->GetType();
        array<MemberInfo^>^ serializableMembers =
            FormatterServices::GetSerializableMembers(thisType, context);

        // Serialize the base class's fields to the info object.
        for each (MemberInfo^ serializableMember in serializableMembers)
        {
            // Do not serialize fields for this class.
            if (serializableMember->DeclaringType != thisType)
            {
                // Skip this field if it is marked NonSerialized.
                if (!(Attribute::IsDefined(serializableMember,
                    NonSerializedAttribute::typeid)))
                {
                    // Get the value of this field and add it to the
                    // SerializationInfo object.
                    info->AddValue(serializableMember->Name,
                        ((FieldInfo^)serializableMember)->GetValue(this));
                }
            }
        }

        // Call the method below to see the contents of the
        // SerializationInfo object.
        DisplaySerializationInfo(info);
    }

private:
    static void DisplaySerializationInfo(SerializationInfo^ info)
    {
        Console::WriteLine("Values in the SerializationInfo:");
        for each (SerializationEntry^ infoEntry in info)
        {
            Console::WriteLine("Name={0}, ObjectType={1}, Value={2}",
                infoEntry->Name, infoEntry->ObjectType, infoEntry->Value);
        }
    }

protected:
    Manager(SerializationInfo^ info,
        StreamingContext context) : Employee(nullptr)
    {
        // Get the set of serializable members for the class and base classes.
        Type^ thisType = this->GetType();
        array<MemberInfo^>^ serializableMembers =
            FormatterServices::GetSerializableMembers(thisType, context);

        // Deserialize the base class's fields from the info object.
        for each (MemberInfo^ serializableMember in serializableMembers)
        {
            // Do not deserialize fields for this class.
            if (serializableMember->DeclaringType != thisType)
            {
                // For easier coding, treat the member as a FieldInfo object
                FieldInfo^ fieldInformation = (FieldInfo^)serializableMember;

                // Skip this field if it is marked NonSerialized.
                if (!(Attribute::IsDefined(serializableMember,
                    NonSerializedAttribute::typeid)))
                {
                    // Get the value of this field from the
                    // SerializationInfo object.
                    fieldInformation->SetValue(this,
                        info->GetValue(fieldInformation->Name,
                        fieldInformation->FieldType));
                }
            }
        }

        // Deserialize the values that were serialized for this class.
        title = info->GetString("title");
    }

public:
    virtual String^ ToString() override
    {
        return String::Format("{0} -> {1}", title, Employee::ToString());
    }
};

int main()
{
    Stream^ stream = gcnew MemoryStream();
    IFormatter^ formatter = gcnew BinaryFormatter();
    Manager^ m = gcnew Manager();
    Console::WriteLine(m->ToString());
    formatter->Serialize(stream, m);

    stream->Position = 0;
    m = (Manager^) formatter->Deserialize(stream);
    Console::WriteLine(m->ToString());
}

// This code produces the following output.
//
//  Manager -> Employee -> Person
//  Values in the SerializaitonInfo:
//  Name=title, ObjectType=System.String, Value=Manager
//  Name=Employee+title, ObjectType=System.String, Value=Employee
//  Name=Person+title, ObjectType=System.String, Value=Person
//  Manager -> Employee -> Person
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Security.Permissions;


// Person is a serializable base class.
[Serializable]
public class Person
{
    private String title;

    public Person(String title)
    {
        this.title = title;
    }

    public override String ToString()
    {
        return String.Format("{0}", title);
    }
}

// Employee is a serializable class derived from Person.
[Serializable]
public class Employee : Person
{
    private String title;

    public Employee(String title) : base("Person")
    {
        this.title = title;
    }

    public override String ToString()
    {
        return String.Format("{0} -> {1}", title, base.ToString());
    }
}

// Manager is a serializable and ISerializable class derived from Employee.
[Serializable]
public class Manager : Employee, ISerializable
{
    private String title;

    public Manager() : base("Employee") 
    {
        this.title = "Manager";
    }

    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {

        // Serialize the desired values for this class.
        info.AddValue("title", title);

        // Get the set of serializable members for the class and base classes.
        Type thisType = this.GetType();
        MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);

        // Serialize the base class's fields to the info object.
        for (Int32 i = 0; i < mi.Length; i++)
        {
            // Do not serialize fields for this class.
            if (mi[i].DeclaringType == thisType) continue;

            // Skip this field if it is marked NonSerialized.
            if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;
         
            // Get the value of this field and add it to the SerializationInfo object.
            info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this));
        }

        // Call the method below to see the contents of the SerializationInfo object.
        DisplaySerializationInfo(info);
    }
 
    private void DisplaySerializationInfo(SerializationInfo info)
    {
        SerializationInfoEnumerator e = info.GetEnumerator();
        Console.WriteLine("Values in the SerializationInfo:");
        while (e.MoveNext())
        {
            Console.WriteLine("Name={0}, ObjectType={1}, Value={2}", e.Name, e.ObjectType, e.Value);
        }
    }

    [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.SerializationFormatter)]
    protected Manager(SerializationInfo info, StreamingContext context) : base(null)
    {

        // Get the set of serializable members for the class and base classes.
        Type thisType = this.GetType();
        MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);

        // Deserialize the base class's fields from the info object.
        for (Int32 i = 0; i < mi.Length; i++)
        {
            // Do not deserialize fields for this class.
            if (mi[i].DeclaringType == thisType) continue;

            // For easier coding, treat the member as a FieldInfo object
            FieldInfo fi = (FieldInfo) mi[i];

            // Skip this field if it is marked NonSerialized.
            if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;

            // Get the value of this field from the SerializationInfo object.
            fi.SetValue(this, info.GetValue(fi.Name, fi.FieldType));
        }

        // Deserialize the values that were serialized for this class.
        title = info.GetString("title");
    }

    public override String ToString()
    {
        return String.Format("{0} -> {1}", title, base.ToString());
    }
}


public sealed class App
{
    public static void Main()
    {
        Run();
    }

    public static void Run()
    {
        using (Stream stream = new MemoryStream())
	{
            IFormatter formatter = new BinaryFormatter();
            Manager m = new Manager();
            Console.WriteLine(m.ToString());
            formatter.Serialize(stream, m);

            stream.Position = 0;
            m = (Manager) formatter.Deserialize(stream);
            Console.WriteLine(m.ToString());
        }
    }
}
// This code produces the following output.
//
//  Manager -> Employee -> Person
//  Values in the SerializaitonInfo:
//  Name=title, ObjectType=System.String, Value=Manager
//  Name=Employee+title, ObjectType=System.String, Value=Employee
//  Name=Person+title, ObjectType=System.String, Value=Person
//  Manager -> Employee -> Person

備註

目前的類別是標準的列舉值中儲存的值透過剖析SerializationInfoThe current class is a standard enumerator that parses over the values stored in SerializationInfo. 而不是記錄的值,SerializationInfoEnumerator的成員變數會保留指標SerializationInfo,建立它。Instead of recording the values, the SerializationInfoEnumerator keeps pointers to the member variables of the SerializationInfo that created it.

這個類別遵循IEnumerator機制。This class follows the IEnumerator mechanism.

屬性

Current Current Current Current

取得目前正在檢查的項目。Gets the item currently being examined.

Name Name Name Name

取得目前正在檢查的項目名稱。Gets the name for the item currently being examined.

ObjectType ObjectType ObjectType ObjectType

取得目前正在檢查的項目型別。Gets the type of the item currently being examined.

Value Value Value Value

取得目前正在檢查的項目值。Gets the value of the item currently being examined.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
MoveNext() MoveNext() MoveNext() MoveNext()

更新列舉值至下一個項目。Updates the enumerator to the next item.

Reset() Reset() Reset() Reset()

將列舉值重設為第一個項目。Resets the enumerator to the first item.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

明確介面實作

IEnumerator.Current IEnumerator.Current IEnumerator.Current IEnumerator.Current

取得集合中的目前項目。Gets the current item in the collection.

適用於

另請參閱