在 WP7 Silverlight 中保存游戏的简单方法?
在 WP7 Silverlight 中保存游戏状态的最佳方法是什么?我更喜欢将它保存在文本文件中.我想在应用程序进入后台时保存游戏(例如有人打电话,用户点击返回"等)或关闭.我该怎么做?
What is the best way to save game state in WP7 Silverlight? I prefer to save it in text file. I want save game when application goes to background (for example someone is calling, user clicks 'back' etc.) or closing. How can I do this?
更新,此代码来自以下文章:
update, this code is from the following articles:
用于后台任务、Toast 和 Tiles 的简单 WP7 Mango 应用简单的WP7芒果后台任务、Toast 和 Tiles 应用:代码说明
IsolatedStorage 运行良好.
IsolatedStorage works well.
这是我用来将一个实例序列化和反序列化到IsolatedStorage 中的json(或xml)的类.这个例子是使用 ServiceStack.Text 但它可以切换出来.
This is a class I use to serialize and deserialize an instance to json (or xml) in IsolatedStorage. This example is use ServiceStack.Text but it can be switched out.
使用、读取和写入:
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();
}
}