0

我正在尝试本教程,因为我想将一些数据保存在 XML 文件中:http: //msdn.microsoft.com/en-us/library/bb203924.aspx

但我在课堂上收到此错误消息SaveGameData

IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);

命名空间不能直接包含字段或方法等成员

XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData)); 

预期的类、委托、枚举、接口或结构

怎么了?

另外,我不知道如何在文件中写入一些东西。例如,如果玩家按下 Escape,我想将分数保存到保存游戏文件中。我怎样才能做到这一点?

public struct SaveGameData
    {
        public string PlayerName;
        public Vector2 AvatarPosition;
        public int Level;
        public int Score;
    }
    // Open a storage container.
IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);

// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();

StorageContainer container = device.EndOpenContainer(result);

// Close the wait handle.
result.AsyncWaitHandle.Close();

string filename = "savegame.sav";

// Check to see whether the save exists.
if (container.FileExists(filename))
   // Delete it so that we can create one fresh.
   container.DeleteFile(filename);

// Create the file.
Stream stream = container.CreateFile(filename);

// Convert the object to XML data and put it in the stream.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
  serializer.Serialize(stream, data);

// Close the file.
stream.Close();

// Dispose the container, to commit changes.
container.Dispose();

// Open a storage container.
IAsyncResult result =
    device.BeginOpenContainer("StorageDemo", null, null);

// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();

StorageContainer container = device.EndOpenContainer(result);

// Close the wait handle.
result.AsyncWaitHandle.Close();

string filename = "savegame.sav";

// Check to see whether the save exists.
if (!container.FileExists(filename))
{
   // If not, dispose of the container and return.
   container.Dispose();
   return;
}

// Open the file.
Stream stream = container.OpenFile(filename, FileMode.Open);

XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

SaveGameData data = (SaveGameData)serializer.Deserialize(stream);

// Close the file.
stream.Close();

// Dispose the container.
container.Dispose();
4

0 回答 0