在UWP中存储和检索复杂类型

时间:2016-07-14 18:18:42

标签: c# uwp

我的ObjectObservableCollection<T>Type TintstringboolPropertyChangedEventHandlerVisibilityObservableCollection个对象。

在应用关闭时存储T对象的最佳方法是什么,然后在再次打开应用时检索它?

1 个答案:

答案 0 :(得分:2)

您将要使用DataContractDataContractSerializer

让我们创建可序列化的类

    public class MySerializableObject
    {

         public int age {get; set;}

         public string name {get; set;}

         public bool isAwesome {get; set;}

    }

这个类的方式不会序列化。我们需要添加一些属性才能使其正常工作。

    [DataContract]
    public class MySerializableObject
    {

          [DataMember]
          public int age {get; set;}
          [DataMember]
          public string name {get; set;}
          [DataMember]
          public bool isAwesome {get; set;}

    }

既然我们已经在DataContract上方添加了类,而DataMember已添加到我们的属性之上,那么它们将是可序列化的。

然后,您可以使用DataContractSerializer来序列化或反序列化您的数据

以下代码不在我的个人资料库中。有用。

    public static void SaveObject(SerializeableObject value)
    {
        Serialize(value, new FileStream(ApplicationData.Current.RoamingFolder.Path 
            + @"\" + value.objectName + ".russ", FileMode.OpenOrCreate));
    }

    public static Object GetObject(string objectName, Type targetType)
    {
        return Deserialize(new FileStream(ApplicationData.Current.RoamingFolder.Path
           + @"\" + objectName + ".russ", FileMode.OpenOrCreate), targetType);
    }

    private static void Serialize(SerializeableObject objectToSerialize, FileStream stream)
    {
        try
        {
            DataContractSerializer serializer = objectToSerialize.GetSerializer();
            serializer.WriteObject(stream, objectToSerialize);
            stream.Dispose();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to Serialize");
            Debug.WriteLine(ex.Message);
        }
    }

    private static Object Deserialize(FileStream stream, Type targetType)
    {
        Object returnValue = null;
        try
        {
            DataContractSerializer serializer =
                  new DataContractSerializer(targetType);

            stream.Position = 0;
            returnValue = serializer.ReadObject(stream);
            stream.Dispose();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to Deserialize");
            Debug.WriteLine(ex.Message);
        }
        return returnValue;
    }

以下是我在上面代码中使用的对象

    [DataContract]
    public class TestSave : SerializeableObject
    {        
        [DataMember]
        public string objectName
        {
            get;
            set;
        }

        [DataMember]
        public bool SaveTestProp { get; set; }

        public DataContractSerializer GetSerializer()
        {
            return new DataContractSerializer(typeof(TestSave));
        }
    }

    public interface SerializeableObject
    {
        string objectName { get; }
        DataContractSerializer GetSerializer();
    }