我在保存游戏时遇到了问题,我花了几个小时寻找解决方案,但没有任何运气。我使用了别人博客上写的代码:
public class SaveandLoad
{
StorageDevice device;
string containerName = "ChainedWingsContainer";
string filename = "mysave.sav";
public struct SaveGame
{
public int s_mission;
}
public void InitiateSave()
{
if (!Guide.IsVisible)
{
device = null;
StorageDevice.BeginShowSelector(PlayerIndex.One, this.SaveToDevice, null);
}
}
void SaveToDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
if (device != null && device.IsConnected)
{
SaveGame SaveData = new SaveGame()
{
s_mission = Game1.mission,
};
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(r);
if (container.FileExists(filename))
container.DeleteFile(filename);
Stream stream = container.CreateFile(filename);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
serializer.Serialize(stream, SaveData);
stream.Close();
container.Dispose();
result.AsyncWaitHandle.Close();
}
}
public void InitiateLoad()
{
if (!Guide.IsVisible)
{
device = null;
StorageDevice.BeginShowSelector(PlayerIndex.One, this.LoadFromDevice, null);
}
}
void LoadFromDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(r);
result.AsyncWaitHandle.Close();
if (container.FileExists(filename))
{
Stream stream = container.OpenFile(filename, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
SaveGame SaveData = (SaveGame)serializer.Deserialize(stream);
stream.Close();
container.Dispose();
//Update the game based on the save game file
Game1.mission = SaveData.s_mission;
}
}
}
但是每当我运行它,我得到这个消息:
类型为"System"的未处理异常。InvalidOperationException'发生在Microsoft.Xna.Framework.Storage.dll
附加信息:一个新的容器不能被打开,直到这个PlayerIndex使用的所有以前的容器被处理掉。
我四处寻找答案,大多数建议都建议使用Using语句。所以我使用Using like So:
void SaveToDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
if (device != null && device.IsConnected)
{
SaveGame SaveData = new SaveGame()
{
s_mission = Game1.mission,
};
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
using (StorageContainer container = device.EndOpenContainer(r))
{
if (container.FileExists(filename))
container.DeleteFile(filename);
Stream stream = container.CreateFile(filename);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
serializer.Serialize(stream, SaveData);
stream.Close();
container.Dispose();
}
result.AsyncWaitHandle.Close();
}
}
但我仍然得到相同的结果。我做错了什么?
这个帖子里的人也有同样的问题,是由using语句范围之外的某种异常处理引起的,导致dispose不能被正确调用。请尝试将using语句包装在Try catch中。
同时,我发现这篇文章在寻找解决方案时很有帮助。
好运。