我一直在关注二进制序列化指南(这里是这个:http: //www.codeproject.com/Articles/1789/Object-Serialization-using-C),我想我终于几乎让它工作了。当我保存文件时创建,但是当我尝试加载时,什么都没有加载。我觉得我已经接近完成这项工作了。任何意见,将不胜感激。这是代码:
保存/加载类
[Serializable()]
public class SaveLoad : ISerializable
{
public int GameDay = Date.GameDay;
public List<Adventurer> Adventurers = FormMain.AdventurerManager.AdventurerList;
public SaveLoad()
{
GameDay = 0;
Adventurers = null;
}
public SaveLoad(SerializationInfo info, StreamingContext ctxt)
{
GameDay = (int)info.GetValue("Date", typeof(int));
Adventurers = (List<Adventurer>)info.GetValue("Adventurers", typeof(List<Adventurer>));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Date", GameDay);
info.AddValue("Adventurers", Adventurers);
}
}
保存/加载方法:
void btnSaveGame_Click(object sender, EventArgs e)
{
SaveLoad save = new SaveLoad();
Stream stream = File.Open("SaveGame.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, save);
stream.Close();
}
void btnLoadGame_Click(object sender, EventArgs e)
{
SaveLoad load = new SaveLoad();
Stream stream = File.Open("SaveGame.osl", FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
load = (SaveLoad)bformatter.Deserialize(stream);
stream.Close();
Date.CalculateDate();
this.Visible = false;
((FormMain)(this.ParentForm)).ControlMainScreen.Visible = true;
}