在WP7 Silverlight中保存游戏的简便方法?

时间:2013-01-17 14:58:47

标签: windows-phone-7 savestate

在WP7 Silverlight中保存游戏状态的最佳方法是什么?我更喜欢将其保存在文本文件中。我希望在应用程序进入后台时保存游戏(例如有人正在呼叫,用户点击“返回”等)或关闭。我怎么能这样做?

1 个答案:

答案 0 :(得分:6)

更新,此代码来自以下文章:

Simple WP7 Mango App for Background Tasks, Toast, and Tiles Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

IsolatedStorage效果很好。

这是我用来在IsolatedStorage中将实例序列化和反序列化为json(或xml)的类。此示例使用ServiceStack.Text,但可以将其切换出来。

使用,读写:

public class MyClass {
    public void Save() {
        MutexedIsoStorageFile.Write(this, "MyClass.json", "MYCLASSJSON");
    }

    public static MyClass Load() {
        return MutexedIsoStorageFile.Read<MyClass>("MyClass.json", "MYCLASSJSON");
    }
}        

public static class MutexedIsoStorageFile
    {
        public static T Read<T>(string fileName, string mutexName) where T : new()
        {
            var mutexFile = new Mutex(false, mutexName);
            var model = new T();
            mutexFile.WaitOne();

            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                using (var stream = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read, store))
                using (var reader = new StreamReader(stream))
                    if (!reader.EndOfStream)
                    {
                        //var serializer = new XmlSerializer(typeof (T));
                        //model = (T) serializer.Deserialize(reader);                       
                        model = JsonSerializer.DeserializeFromReader<T>(reader);
                    }
            }
            finally
            {
                mutexFile.ReleaseMutex();
            }

            return model;
        }

        public static void Write<T>(T data, string fileName, string mutexName)
        {
            var mutexFile = new Mutex(false, mutexName);
            mutexFile.WaitOne();

            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, store))
                {
                    //var serializer = new XmlSerializer(typeof (T));
                    //serializer.Serialize(stream, data);
                    JsonSerializer.SerializeToStream(data, stream);
                }
            }
            finally
            {
                mutexFile.ReleaseMutex();
            }
        }