如何在WP7独立存储中存储类的对象?我想要检索它并在需要时编辑它。
答案 0 :(得分:5)
您需要序列化数据以保存它,然后反序列化它以加载它。您可以找到一个完整的工作示例in this article。
例如,按如下方式标记类和属性:
[DataContract]
public class Employee
{
[DataMember]
public int EmployeeNumber { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
}
构建一个序列化器:
DataContractSerializer mySerializer = new DataContractSerializer(typeof(Employee));
然后通过ReadObject
/ WriteObject
加载/保存。
答案 1 :(得分:1)
你可以使用xml序列化
public static void Serialize<T>(T obj, string fileName)
{
try
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, writerSettings))
{
serializer.Serialize(xmlWriter, obj);
}
stream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
public static T DeSerialize<T>(string fileName)
{
try
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{
throw ex;
}
}