Visual C++ .NET/File Directory/Serializable

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Mark class as Serializable

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
[Serializable]
ref class RoleAttr{
public:
    property int Wisdom;
    RoleAttr(int Wis);
    void Print();
};
RoleAttr::RoleAttr(int Wis)
{
    this->Wisdom       = Wis;
}
void RoleAttr::Print()
{
    Console::WriteLine("Wis: {1}", Wisdom);
}
[Serializable]
ref class Role{
public:
    property String ^Name;
    property String ^Race;
    property String ^Class;
    property RoleAttr ^pattr;

    Role (String ^Name, String ^Race, String ^Class,int Wis);
    void Print();
};
Role::Role (String ^Name, String ^Race, String ^Class,int Wis)
{
    this->Name  = Name;
    this->Race  = Race;
    this->Class = Class;
    this->pattr = gcnew RoleAttr(Wis);
}
void Role::Print()
{
    Console::WriteLine("Name:  {0}", Name);
    Console::WriteLine("Race:  {0}", Race);
    Console::WriteLine("Class: {0}", Class);
    pattr->Print();
}
void main()
{
    Role ^r = gcnew Role("r", "Human", "Thief", 11);
    r->Print();
    FileStream ^plStream = File::Create("Role.dat");
    BinaryFormatter ^bf = gcnew BinaryFormatter();
    bf->Serialize(plStream, r);
    plStream->Close();
    plStream = File::OpenRead("Role.dat");
    Role ^rClone = (Role^)bf->Deserialize(plStream);
    plStream->Close();
    rClone->Print();
}


Serialize nested classes

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
[Serializable]
ref class RoleAttr{
public:
    property int Wisdom;
    RoleAttr(int Wis);
    void Print();
};
RoleAttr::RoleAttr(int Wis)
{
    this->Wisdom       = Wis;
}
void RoleAttr::Print()
{
    Console::WriteLine("Wis: {1}", Wisdom);
}
[Serializable]
ref class Role{
public:
    property String ^Name;
    property String ^Race;
    property String ^Class;
    property RoleAttr ^pattr;

    Role (String ^Name, String ^Race, String ^Class,int Wis);
    void Print();
};
Role::Role (String ^Name, String ^Race, String ^Class,int Wis)
{
    this->Name  = Name;
    this->Race  = Race;
    this->Class = Class;
    this->pattr = gcnew RoleAttr(Wis);
}
void Role::Print()
{
    Console::WriteLine("Name:  {0}", Name);
    Console::WriteLine("Race:  {0}", Race);
    Console::WriteLine("Class: {0}", Class);
    pattr->Print();
}
void main()
{
    Role ^r = gcnew Role("r", "Human", "Thief", 11);
    r->Print();
    FileStream ^plStream = File::Create("Role.dat");
    BinaryFormatter ^bf = gcnew BinaryFormatter();
    bf->Serialize(plStream, r);
    plStream->Close();
    plStream = File::OpenRead("Role.dat");
    Role ^rClone = (Role^)bf->Deserialize(plStream);
    plStream->Close();
    rClone->Print();
}