windows 在独立存储中存储对象列表的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5073925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:13:45  来源:igfitidea点击:

problem Storing a list of Objects in Isolated Storage

c#windowslistwindows-phone-7stackpanel

提问by RJDubz

I am trying to store a list of objects I created in the isolated storage and be able to display them in a list by auto generating a title for them. So far the code works but once I tombstone the app and start it up all my data is saved except for the list of objects. I think my problem may be with how I initialize the list in the first place, or possibly how I am displaying the names. Any help is appreciated.

我正在尝试存储我在独立存储中创建的对象列表,并能够通过自动为它们生成标题来将它们显示在列表中。到目前为止,代码有效,但是一旦我对应用程序进行墓碑删除并启动它,除了对象列表之外,我的所有数据都将被保存。我认为我的问题可能在于我如何初始化列表,或者可能是我如何显示名称。任何帮助表示赞赏。

this code is in my App.xaml.cs:

这段代码在我的 App.xaml.cs 中:

public partial class App : Application
    {
      public List<my_type> testList = new List<my_type>();

        void loadvalues()
        {
         IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
         List<my_Type> L;
         if (settings.TryGetValue<List<DrinkSesh>>("Storage", out L))
         { testList = L; }
        }

        void savevalues()
        {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        settings["Storage"] = testList;
        settings.Save();
        }
     }

This code is on my mainPage to add the items to the list:

此代码位于我的 mainPage 上,用于将项目添加到列表中:

(Application.Current as App).testList.Add(new my_type());

and this code is to implement the titles onto the screen on a different page:

这段代码是在不同页面的屏幕上实现标题:

 public different_class()
{
        {
                InitializeComponent();
                for (i = 0; i < (Application.Current as App).testList.Count; i++)
                {
                    CreateATextBlock((Application.Current as    App).testList[i].Title_ToString(), i);
                }
        }

        private void CreateATextBlock(String title,int num)
        {
            testblockname = new TextBlock();
            testblockname.Text = (num + 1) + ". " + title;
            DrList.Children.Add(testblockname);
        }
}

Thank you in advance!

先感谢您!

回答by Steve Chadbourne

Here is the code I use to save and load lists of objects from isolated storage.

这是我用来从独立存储中保存和加载对象列表的代码。

public class IsoStoreHelper
{
    private static IsolatedStorageFile _isoStore;
    public static IsolatedStorageFile IsoStore 
    { 
        get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
    }

    public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class
    {
        if (!IsoStore.DirectoryExists(folderName))
        {
            IsoStore.CreateDirectory(folderName);
        }

        string fileStreamName = string.Format("{0}\{1}.dat", folderName, dataName);

        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore))
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
            dcs.WriteObject(stream, dataList);
        }
    }

    public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class
    {
        ObservableCollection<T> retval = new ObservableCollection<T>();

        if (!IsoStore.DirectoryExists(folderName))
        {
            IsoStore.CreateDirectory(folderName);
        }

        string fileStreamName = string.Format("{0}\{1}.dat", folderName, dataName);

        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
        {
            if (stream.Length > 0)
            {
                DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                retval = dcs.ReadObject(stream) as ObservableCollection<T>;
            }
        }

        return retval;
    }
}

回答by Matt Lacey

By simply adding your collection (List) to your IsolatedStorageSettings you are relying on the built in serializer (the DataContractSerializer) to serialize your object for persisting to disk.

通过简单地将您的集合(列表)添加到您的 IndependentStorageSettings,您将依赖于内置的序列化程序(DataContractSerializer)来序列化您的对象以保存到磁盘。

Are you sure your object can be correctly serialized and deserialized?

您确定您的对象可以正确序列化和反序列化吗?

Doing this yourself is probably the easiest way to do this.

自己做这件事可能是最简单的方法。

If you do this yourself, not that: - DataContractSerializer is slow - DataContractJsonSerializer is faster - Json.net is faster still - Binary serialization is fastest.

如果你自己这样做,而不是: - DataContractSerializer 很慢 - DataContractJsonSerializer 更快 - Json.net 仍然更快 - 二进制序列化最快。

When serializing yourself you should also save in an IsolatedStorageFile rahter than in the settings. This can help with performance and also adds flexibility which can aid debugging and testing.

对自己进行序列化时,您还应该保存在 IsolatedStorageFile 中而不是在设置中。这有助于提高性能,还增加了有助于调试和测试的灵活性。