windows-phone-8 – 在Windows Phone 8应用程序中序列化和反序列化对象列表

给出一些对象列表:
List<Car> carlist = new List<Car>();

如何将此列表序列化为XML或二进制文件并将其反序列化?

到目前为止,我有这个,但它不起作用.

//IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication();
//IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml",FileMode.Create,isFile);
//DataContractSerializer ser = new DataContractSerializer();
//XmlWriter writer = XmlWriter.Create(ifs);
//ser.WriteObject(writer,carlist);
我正在使用这些方法从/到IsolatedStorage的XML文件中保存和加载:
public static class IsolatedStorageOperations
{
    public static async Task Save<T>(this T obj,string file)
    {
        await Task.Run(() =>
            {
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream stream = null;

                try
                {
                    stream = storage.CreateFile(file);
                    XmlSerializer serializer = new XmlSerializer(typeof (T));
                    serializer.Serialize(stream,obj);
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.dispose();
                    }
                }
            });
    }

    public static async Task<T> Load<T>(string file)
    {

        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        T obj = Activator.CreateInstance<T>();

        if (storage.FileExists(file))
        {
            IsolatedStorageFileStream stream = null;
            try
            {
                stream = storage.OpenFile(file,FileMode.Open);
                XmlSerializer serializer = new XmlSerializer(typeof (T));

                obj = (T) serializer.Deserialize(stream);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.dispose();
                }
            }
            return obj;
        }
        await obj.Save(file);
        return obj;
    }
}

您可以在catch()中自定义错误处理.

此外,您可以根据需要调整Load方法,在我的情况下,我尝试从文件加载,如果不存在,则创建认值并根据构造函数放置提供的类型的认序列化对象.

更新:

假设你有这样的汽车列表:

列表与LT;汽车> carlist = new List< Car>();

要保存,您可以将它们称为await carlist.Save(“myXML.xml”);,因为它是异步任务(异步).

要加载,var MyCars = await IsolatedStorageOperations.Load<列表与LT;车> &GT( “myXML.xml”). (我想,到目前为止,我没有像这样使用它作为列表...

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...