【问题标题】:List of Objects Serialization xml fault对象序列化 xml 错误列表
【发布时间】:2012-11-16 03:41:54
【问题描述】:

我正在制作一个 WPF 应用程序,我在其中保存我的 WPF 应用程序退出时的对象列表。并在系统启动时获取对象列表。最初一切正常。但有时它会给出序列化异常。得到异常后,我查看了 xml 序列化文件。但在我看来,抛出异常是因为 xml 文件没有正确形成。当我纠正它时。它再次运行良好。

public static class IsolatedStorageCacheManager<T>
{
    public static void store(T loc)
    {
        IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null);
        using(IsolatedStorageFileStream fileStream=appStore.OpenFile("myFile21.xml",FileMode.OpenOrCreate))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(fileStream, loc);
        }
    }
    public static T retrieve()
    {
        T obj = default(T);
        IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null);
        if (appStore.FileExists("myFile21.xml"))
        {
            using (IsolatedStorageFileStream fileStream = appStore.OpenFile("myFile21.xml", FileMode.Open))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                try
                {
                    obj = (T)serializer.ReadObject(fileStream);
                }
                catch (SerializationException e)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
        return obj;
    }
}

【问题讨论】:

  • 您传入的一个或多个对象是否有可能不可序列化?
  • XML 文件格式不正确是什么意思?您必须如何纠正它才能使其正常工作?

标签: c# wpf


【解决方案1】:

首先要做的是确保传递给store 的对象属于supported by the DataContractSerializer 类型。

最简单的做法是自己检查所有store 呼叫。

您还可以创建一种验证方法,甚至更好,看看是否有其他人已经实现了。此方法可以验证loc 对象并返回boolean 并在store 方法的开头在System.Diagnostics.Debug.Assert 调用中调用,以便它仅在调试配置上运行。请注意,尽管此方法可能非常棘手,因为您必须针对 DataContractSerializer 规范中提到的所有情况验证类型 T,并且如果 T 是泛型,还要验证 T 的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 2017-01-24
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多