1

如何在 WP7 隔离存储中存储类的对象?我想检索它并在需要时对其进行编辑。

4

2 回答 2

5

您需要序列化数据以保存它,然后反序列化它以加载它。您可以在本文中找到一个完整的工作示例。

例如,将类和属性标记如下:

[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

于 2012-05-22T05:32:59.313 回答
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;
      }
    } 
于 2012-05-22T05:55:36.883 回答