我正在创建一个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;
}
}
答案 0 :(得分:0)
要做的第一件事是确保传递给store
的对象属于supported by the DataContractSerializer类型。
最简单的方法是自己检查所有store
个电话。
您还可以创建验证方法,甚至更好,看看是否有其他人已经实现了验证方法。此方法可以验证loc
对象并返回boolean
,并在System.Diagnostics.Debug.Assert调用内的store
方法的开头调用,以便它只在调试时运行组态。请注意,这种方法可能非常棘手,因为您必须为DataContractSerializer
规范中提到的所有情况验证类型T,并且T是一般验证T的参数。