【问题标题】:Saving an array in Windows Phone 7 Xna在 Windows Phone 7 Xna 中保存数组
【发布时间】:2014-04-14 04:32:04
【问题描述】:

我需要在我的 xna 游戏中为 wp7 保存一个数组。我在想我可以使用 XmlSerializer 类,但我对如何使用一无所知。这是合适的方法吗?有什么建议么?提前致谢。

【问题讨论】:

标签: arrays windows-phone-7 xna isolatedstorage xmlserializer


【解决方案1】:

应该这样做:

private static void DoSaveGame(StorageDevice device)
{
    // Create the data to save.
    SaveGameData data = new SaveGameData();
    data.PlayerName = "Hiro";
    data.AvatarPosition = new Vector2(360, 360);
    data.Level = 11;
    data.Score = 4200;

    // 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();
}

private static void DoLoadGame(StorageDevice device)
{
    // 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);

    // Read the data from the file.
    XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
    SaveGameData data = (SaveGameData)serializer.Deserialize(stream);

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

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

    // Report the data to the console.
    Debug.WriteLine("Name:     " + data.PlayerName);
    Debug.WriteLine("Level:    " + data.Level.ToString());
    Debug.WriteLine("Score:    " + data.Score.ToString());
    Debug.WriteLine("Position: " + data.AvatarPosition.ToString());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多